Thomas Timmermans
Thomas Timmermans

Reputation: 426

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();
}

Upvotes: 1

Views: 2177

Answers (3)

Savo
Savo

Reputation: 11

Try:

Order::query()
    ->select(['pickup_date', 'pickup_time', 'remark'])
    ->with(['products:name,price,quantity'])
    ->paginate($length);

Upvotes: 1

STA
STA

Reputation: 34668

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);

Upvotes: 2

hammad khan
hammad khan

Reputation: 65

You are missing one thing,you should add product id in outer select.

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

I hope it would be helpful

Upvotes: 1

Related Questions