Laravel Eager Loading - Load only specific columns

前端 未结 7 1435
梦毁少年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 00:48

    Sometimes you need to make your relation generic so that can call on your ease.

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

    and while fetching you can mention columns you need.

    $owners = Owner::with(['car' => function($query) { // eager loading
                $query->select('emailid','name');
               }
              ])->get();
    
    foreach($owners as $owner){
        $owner->car->emailid;
        $owner->car->name;
    }
    

提交回复
热议问题