Laravel Eloquent: eager loading of multiple nested relationships
50,207
Solution 1
You can do
$books = App\Book::with('author.contacts','author.publishers')->get();
Solution 2
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
So, now you can try
$books = App\Book::with(['author' => function($author){
$author->with(['contacts', 'publishers'])->get();
}])->get();
Author by
DrivingInsanee
Updated on July 05, 2022Comments
-
DrivingInsanee almost 2 years
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?
-
Chaudhry Waqas about 7 yearsjust to add, it will fetch the corresponding author data as well ofcourse.
-
Todd almost 7 yearsFollow-up: I have a much more complex model and want to return a single collection, but like the original poster, wish I could use multiple nested relationships at a lower child level like
$event = event::with(['streams.experiences.selectors.['digitalprops.frames','filters']','streams.datacaptures'])->find($eventcode);
-
tisuchi almost 6 years@Todd How do you execute this code in Laravel?
$event = event::with(['streams.experiences.selectors.['digitalprops.frames','filters']','streams.datacaptures'])->find($eventcode);
. It shouldn't work...! -
Todd almost 6 yearsRight @tisuchi -- I said I WISH I could... sorry for the confusion.
-
Adam almost 5 yearsThis is the best overview how to eager load efficiently!
-
msbomrel over 4 yearsdoes author is table name or what?
-
Elisha Senoo over 4 years@msbomrel, author is a relationship method in the Book class
-
kristoffer over 3 yearsThis looks amazing! Thanks for your input!
-
Luciano over 2 yearsI think that
->get()
is not needed at all within the closure