thau0x01
thau0x01

Reputation: 892

Retrieve custom fields from parent table and and some other custom fields from child models using with in Laravel/Eloquent

i'm having the following issue on a projetct, i'm trying to retrieve some fields from a model and other specific fields from a child relationship, but when i use the ->select('id') statement, it just retrieve the id field from my parent model and all child relationships comes as null values, for example:

$someData = App\Book::with(['author:id,name,email', 'publisher:id,name,address'])->select('id')->get();

I just want to retrieve the book id; the author id, name and email fields and finally 'id, name and address' fields from the publisher table, this is clear? Can someone help me?

Upvotes: 0

Views: 191

Answers (1)

Chin Leung
Chin Leung

Reputation: 14941

If you perform a ->select('id'), Laravel does not have the foreign key that it needs for the relationships.

Simply add the foreign key to the select:

->select('id', 'author_id', 'publisher_id')

So it should look like this:

$someData = App\Book::with(['author:id,name,email', 'publisher:id,name,address'])
    ->select('id', 'author_id', 'publisher_id')
    ->get();

Upvotes: 1

Related Questions