在laravel中查询关系模型5.3
问题描述:
我有3个名为“User”,“Order”,“Orders_products”的模型。该关系如下:在laravel中查询关系模型5.3
- 用户有很多订单
- 订单有许多Orders_products
下面是这个模型的代码
用户模型
public function order(){
return $this->hasMany('App\Order');
}
订货型号
public function order_product(){
return $this-> hasMany('App\Orders_product');
}
public function user(){
return $this-> belongsTo('App\User');
}
Orders_products型号
public function order(){
return $this->belongsTo('App\Order');
}
的用户可以有多个订单,所有订单可以有多个订购的产品。我如何获得特定用户的所有订单以及订购的产品。
答
$Order = Order::with('order_product')->where(['user_id'=>$id])->get();
其中$id
是user_id
答
用户模型
public function order()
{
return $this->hasMany(Order::class);
}
订货型号
public function user()
{
return $this->hasOne(User::class);
}
public function orders_products()
{
return $this->belongsToMany(Orders_products::class);
}
Orders_products
public function order()
{
return $this->belongsToMany(Order::class);
}
答
这应该工作,$用户ID是怎么过的,你指定你的应用程序的用户ID。
User::with('order_product.order')->where('id', $usersid)->get();
这将返回一个空对象。 –
$ Order = Order :: with('order_product') - > where(['user_id'=> $ id]) - > get();这对我有效。感谢您的赞赏@ATechGuy –
标记为答案请 – ATechGuy