Whats wrong with Area::with('province', 'province.country')->get();
Jul 30, 2016
8
Level 1
eloquent multiple joins
i have 3 tables Country->Province->Area now i want to use eloquent model to get the data
i want to get the area with its related province with its related country using eloquent
i dont want to use query builder because im using field mutators that i befit from. thanks using laravel 5.2
Level 14
Fun fact: You can Eager Load using closures:
Area::select([
'id',
'province_id',
'<column> AS <alias>',
/* ... */
])->with([
'province' => function($query) {
return $query->select([
'id',
'country_id',
'<column> AS <alias>',
/* ... */
]);
},
'province.country' => function($query) {
return $query->select([
'id',
'<column> AS <alias>',
/* ... */
]);
}
])->get();
Result:
Illuminate\Support\Collection: {
#items: [
0 => App\Models\Area {
'id' => 1,
'province_id' => 1
'<alias>' => /* ... */
'province' => App\Models\Province {
'id' => 1
'country_id' => 1,
'<alias>' => /* ... */
'country' => App\Models\Country {
'id' => 1
'<alias>' => /* ... */
}
}
}
/* ... */
]
}
Get be sure to pull in any Foreign Keys / Primary Keys that are used in the joins for the Eager Loading, or else the relationship will return an empty set.
1 like
Please or to participate in this conversation.