Laravel 5 eager loading belongs to relation
I have 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 a relationship that belongs to To, for example:
public function title()
{
return $this->engineAd->engine->title;
}
For the first relation Ad -> AdEngine, I used download to get all the AdEngine:
$ads = Ad::with('engineAd');
But for the AdEngine -> Engine relationship, Laravel generates an additional request for each iteration, can I use a downloadable load or something similar here?
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
Thank.
+3
source to share