Search code examples
laraveleloquenteager-loading

Laravel: Eager loading specific columns


Why does

Order::with(['products'=>function($q){
    $q->select('name', 'price', 'quantity')->orderBy('name','asc');
  }])->paginate($length);

returns all orders with their respective product data, but

Order::with(['products'=>function($q){
    $q->select('name', 'price', 'quantity')->orderBy('name','asc');
  }])->select('pickup_date', 'pickup_time', 'remark')->paginate($length);

gives me all order data I want, but an empty products array?

I want to select some specific columns from the order table with some specific columns from the products table. How can I do this?

FYI: Orders-products have a many-to-many relationship with models: Order Model:

public function products()
{
    return $this->belongsToMany('App\Models\Product')->withTimestamps();
}

Product Model:

public function orders()
{
  return $this->belongsToMany('App\Models\Order')->withTimestamps();
}

Solution

  • You need to select like this way :

    Order::with(['products'=>function($q){
        $q->orderBy('name','asc');
      }])->select('products.name as name','products.price as price','products.quantity as quantity','orders.pickup_date as pickup_date', 'orders.pickup_time as pickup_time', 'orders.remark as remark')->paginate($length);
    

    Or without sub query :

    Order::with('products')
       ->select('products.name as name','products.price as price','products.quantity as quantity','orders.pickup_date as pickup_date', 'orders.pickup_time as pickup_time', 'orders.remark as remark')
       ->orderBy('name','asc');
       ->paginate($length);