Rui Costa
Rui Costa

Reputation: 43

How to select specific columns from nested relationships in a query with Laravel

Model A, has BelongsTo with Model B. Model B has BelogsTo wit Model C

So, I need to make a query and i need to get * from Model A, 2 columns from Model B and other 2 columns from Model C

ModelA::query()
->with([
'relationModelB' => function ($query) {
$query->select('id', 'column');
},
'relationModelB.relationModelC' => function ($query) {
$query->select('id', 'column');
}
])
->where('id', $id)
->first();

This return all from A, 2 columns from B, but C returns null.

If, I try this query, it returns well, alls columns from 3 models.

ModelA::query()
->with(['relationModelB', 'relationModelB'])
->where('id', $id)
->first();

What is missing in the first query, to get specific columns from the relation of the relation?

Upvotes: 2

Views: 2980

Answers (2)

Claudio Aldrighetti
Claudio Aldrighetti

Reputation: 13

LARAVEL 8

When you want to select specific columns of relationships, both nested or not, you must include the ones involved into the relationship, because Eloquent needs them to resolve the relationship itself (as told by lagbox in the comments).

In your situation, you must include the foreign key column of relationModelB that refers to relationModelC (let's say relationModelC_id). You can handle this in the following way:

modelA::with(
    "relationModelB.relationModelC:id,column",
    "relationModelB:id,column,relationModelC_id"
  )
  ->find($id);

This works for belongsTo relationships that have only one foreign key column. For example, if the relationship is a morphTo, you must include also the type column.

Upvotes: 1

Donkarnash
Donkarnash

Reputation: 12835

Try the following

ModelA::query()
    ->with(['relationModelB' => function ($query) {
        $query->with(['relationModelC' => function($query){
            $query->select('id', 'column');
        })
        ->select('id', 'column');
    }])
    ->where('id', $id)
    ->first();

OR

ModelA::query()
    ->with(['relationModelB' => function ($query) {
        $query->with('relationModelC:id,column')
            ->select('id', 'column');
    }])
    ->where('id', $id)
    ->first();

Upvotes: 6

Related Questions