Laravel Eager Loading - Load only specific columns

前端 未结 7 1406
梦毁少年i
梦毁少年i 2020-12-05 00:35

I am trying to eager load a model in laravel but only return certain columns. I do not want the whole eager loaded table being presented.

public function car         


        
相关标签:
7条回答
  • 2020-12-05 01:05

    The easiest thing you can do is go by the documentation and do the following thing for getting only specific columns without any extra line of code or closure. Follow steps,

    public function car(){
        return $this->hasOne('Car', 'id');
    }
    

    then when you eager load the relation select only selected columns

    $owner = $this->owner
    ->where('id', 23)
    ->with('car:id,owner_id,emailid,name')   //no space after comma(, ) and id has to be selected otherwise it will give null
    

    Hope this works, have a great day.

    0 讨论(0)
提交回复
热议问题