Nedder
Nedder

Reputation: 68

How to limit the columns returned with a nested relationship - Laravel Eloquent

I'm trying to limit the columns returned on an eloquent relationship with no luck.

The following works:

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

but what I need does not work:

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

Upvotes: 0

Views: 635

Answers (1)

Joseph Ajibodu
Joseph Ajibodu

Reputation: 1656

You are eager loading specific columns.

When using this feature, you should always include the id column and any relevant foreign key columns in the list of columns you wish to retrieve.

So check you company table and make sure you add all foreign key columns,

For example: If this is my company table has a column called owner_id, address_id, you have to add it to the with() method like this.

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

Upvotes: 1

Related Questions