问题描述
为什么
Order::with(['products'=>function($q){
$q->select('name','price','quantity')->orderBy('name','asc');
}])->paginate($length);
返回所有带有其各自产品数据的订单,但是
Order::with(['products'=>function($q){
$q->select('name','asc');
}])->select('pickup_date','pickup_time','remark')->paginate($length);
是否提供了我想要的所有订单数据,但产品数组为空?
我想从订单表中选择一些特定列,从产品表中选择一些特定列。我该怎么办?
仅供参考: 订单产品与模型之间存在多对多关系: 订单型号:
public function products()
{
return $this->belongsToMany('App\Models\Product')->withTimestamps();
}
产品型号:
public function orders()
{
return $this->belongsToMany('App\Models\Order')->withTimestamps();
}
解决方法
您需要这样选择:
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);
或不带子查询:
Order::with('products')
->select('products.name as name','orders.remark as remark')
->orderBy('name','asc');
->paginate($length);
,
您缺少一件事,应该在外部选择中添加产品ID。
Order::with(['products'=>function($q){
$q->select('name','price','quantity')->orderBy('name','asc');
}])->select('product_id','pickup_date','pickup_time','remark')->paginate($length);
我希望这会有所帮助