0

If I have a query: MyModal::with('relation1.relation2')->get(), how can I limit the fields selected from relation1?

MyModal::with('relation1:column1,column2')->with('relation1.relation2')->get() selects all fields on relation1.

MyModal::with('relation1:column1,column2.relation2')->get() gives an SQL error because it tries to find a column named column2.relation2.

I'm not sure what other approach there could be, so is this possible, or will fetching nested relations always fetch all fields on the first relation?

2 Answers 2

1

You should do column select after relation select: MyModal::with(['relation1.relation2', 'relation1:column1,column2'])->get()

Or you can define it in model itself

public function relation1()
{
    return $this->hasOne(Relation1::class)->select(['column1', 'column2']);
}
Sign up to request clarification or add additional context in comments.

Comments

0
Model::query()
->with(array('relation1' => function($query) {
    $query->select('column1', 'column2');
},'relation2' => function($query) {
    $query->select('column1', 'column2');
}))
->get();

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.