mldso's avatar
Level 1

Nested Eager Loading with Specific Columns

Hallo everyone,

in Laravel Docs there is this code example:

$books = Book::with([
    'author' => [
        'contacts',
        'publisher',
    ],
])->get();

and also the possiblity to specify columns:

$books = Book::with('author:id,name,book_id')->get();

I wanted to combine these two like this:

$books = Book::with([
    'author:id,name' => [
        'contacts:id,name',
        'publisher:id,name,address',
    ],
])->get();

it did not work as expected. When there is a nesting like above, the nested ones do not get loaded and stay null! Is this possible at all, or am I doing something wrong here?

0 likes
3 replies
mldso's avatar
Level 1

I tried to use a foreach and go through each row like:

"author:id,name",
"author.contact:id,name",
"author.publisher:id,name,address"

This also did not work. Now I get the nested ones correctly, but the top level will have all of its columns loaded, because in nested ones it gets loaded again.

mldso's avatar
Level 1

@tykus thank you for your reply. That was the problem!

Please or to participate in this conversation.