2

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?

2
  • 2
    Welcome to SO ... you have to make sure to select any columns that would be needed for the relationship (ids, foreign keys) Commented Nov 30, 2020 at 17:07
  • Like I said, if I don't specify, columns, like a select * from, all comes allright, but are too much columns.... Commented Nov 30, 2020 at 17:10

2 Answers 2

6

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();
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.