Search code examples
phplaravellaravel-7

Selecting only certain columns during nested relation


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?


Solution

  • 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']);
    }