Search code examples
laraveleloquenteager-loading

Laravel eloquent with relation data (Eager Loading)


I have two database tables items and measurement_units - item has measurement unit.

Now the problem is I want to select a particular column from items and some column from measurement_unit. I want to use Eager loading

e.g.

$items_with_mu = Item::with("measurement_unit")->select(["item_name", "item_stock"])->first();

When accessing measurement_unit. It returns null. Without the select function it returns data(measurement_unit).

$items_with_mu->measurement_unit;

can anyone help me and sorry for my English.


Solution

  • Try this

    Item::with(['measurement_unit' => function($q) { 
               $q->select('id','unit_column');   //specified measurement_unit column
          }])
         ->select('id','measurement_unit_id','item_name')
         ->get();
    
    

    If your laravel version is >=5.5 then you can write in a single line

    Item::with('measurement_unit:id,unit_column')
         ->select('id','measurement_unit_id','item_name')
         ->get()