Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 5 eager loading belongsTo relation

i'm having a problem with Laravel 5 and Eloquent. I have 3 models called Ad, AdEngine and Engine:

class Ad 
{
    ...
    public function engineAd()
    {
        return $this->belongsTo('App\Models\EngineAd', 'engine_ad_id', 'id');
    }
    ...
}

class EngineAd 
{
    ...
    public function engine()
    {
        return $this->belongsTo('App\Models\Engine', 'engine_id', 'id');
    }
    ...
}

class Engine {...}

Inside my Ad Class, i have a method called title that uses the relation belongsTo, like this:

public function title() 
{
    return $this->engineAd->engine->title;
}

For the first relation Ad -> AdEngine i used eager loading to get all AdEngine:

$ads = Ad::with('engineAd');

But for the relation AdEngine -> Engine, Laravel generates an extra query for every iteration, can i use eager loading or something like this here too?

select * from `engine` where `engine`.`id` = '1' limit 1
select * from `engine` where `engine`.`id` = '2' limit 1
select * from `engine` where `engine`.`id` = '3' limit 1

Thanks.

like image 909
Diego Schell Fernandes Avatar asked Dec 25 '22 16:12

Diego Schell Fernandes


1 Answers

Try using $ads=Ad::with('engineAd.engine')

like image 183
MstfAsan Avatar answered Dec 27 '22 21:12

MstfAsan