Laravel Eloquent: eager loading of multiple nested relationships
LaravelEloquentEager LoadingLaravel Problem Overview
What laravel says:
$books = App\Book::with('author.contacts')->get();
What I need is something like this
$books = App\Book::with('author[contacts,publishers]')->get();
where we eager load multiple relationships within a relationship.
Is this possible?
Laravel Solutions
Solution 1 - Laravel
You can do
$books = App\Book::with('author.contacts','author.publishers')->get();
Solution 2 - Laravel
Laravel documentation on eager loading recommends listing the relationships in an array as follows:
$books = App\Book::with(['author.contacts', 'author.publishers'])->get();
You can have as many relationships as desired. You can also specify which columns should be included for a relationship like this:
//only id, name and email will be returned for author
//id must always be included
$books = App\Book::with(['author: id, name, email', 'author.contacts', 'author.publishers'])->get();
You may also add constrains as follows:
$books = App\Book::with(['author: id, name, email', 'author.contacts' => function ($query) {
$query->where('address', 'like', '%city%');
}, 'author.publishers'])->get();
Solution 3 - Laravel
So, now you can try
$books = App\Book::with(['author' => function($author){
$author->with(['contacts', 'publishers'])->get();
}])->get();
Solution 4 - Laravel
When eager load nested relationships and we want to select just some columns and not all using relationship:id,name
, always include the foreign key to the nested models, else they won't load at all.
Fort example, we have orders that have identities that have addresses.
This will not load the address:
User::orders()
->with('identity:id,name', 'identity.address:id,street')
This will load the address because we have supplied the address_id
foreign key:
User::orders()
->with('identity:id,address_id,name', 'identity.address:id,street')