4
votes

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.

2

2 Answers

5
votes

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

5
votes

You can use nested relations as well using with():

$ads = Ad::with(['engineAd', 'engineAd.engine']);