Laravel Eager Loading - Load only specific columns

前端 未结 7 1436
梦毁少年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:46

    The answers from shahrukh-anwar and Bogdan are both excellent and led me to solving my version of this problem.

    However, there's one critical piece i would add for clarification (even the docs don't mention it).

    Take the following, which was still broken for me:

    Car::with('owner:id,name,email')->get(['year', 'vin']); 
    

    You rarely see specific column selection on the primary model (->get(...)) so it's easy to forget: your selection needs the foreign key column:

    Car::with('owner:id,name,email')->get(['owner_id', 'year', 'vin']);
    

    Sure, it seems obvious once you make the mental connection between with using a Closure and this syntax, but still, easy to overlook.

    When you have tables with 30+ columns and only need 3 of them, this might keep your memory load down a bit.

提交回复
热议问题