[英]Query eloquent relationship with more than one column
玩弄laravel雄辯的關系。 我有這些關系。
訂購:
id
id_customer
Order.php
public function orderDetails(){
return $this->hasMany('App\OrderDetail', 'order_id');
}
訂單詳情
id
order_id
product_id
quantity
OrderDetail模型
public function product()
{
return $this->hasMany('App\Product', 'id', 'id');
}
public function order(){
return $this->belongsTo('App\Order', 'order_id', 'id');
}
產品
id name price
dd($ this-> order-> with('orderDetails')-> get();
我可以使用包含在訂單詳細信息中的產品ID來獲取訂單和orderdetails。 但是我希望能夠獲得產品的名稱,以便可以顯示它。
我運行哪種查詢或更好的方式來定義我的關系?
使用嵌套的渴望加載 :
$this->order->with('orderDetails', 'orderDetails.product')->get();
關系應該是belongsTo()
,但不能是hasMany()
:
public function product()
{
return $this->belongsTo('App\Product', 'product_id', 'id');
}
另外,您可以在此處使用多對多關系。 但是只有在合適的時候。
就像對您提出的關系建議一樣,對於訪問此問題作為參考的每個人,這是我可能實現此目標和我的觀點的一種方法。
它的實際產品屬於許多訂單,而訂單屬於許多產品。 我看到訂單詳細信息是關鍵。 您也可以為此創建模型。
products
表
id
customer_id
Product.php
public function orders()
{
return $this->belongsToMany(Order::class, 'order_details', 'order_id', 'product_id')->withPivot('quantity');
}
orders
表
id
name
price
Order.php
public function products()
{
return $this->belongsToMany(Product::class, 'order_details', 'product_id', 'order_id')->withPivot('quantity');
}
我可能不會創建OrderDetail
因為沒有對該表的可靠引用。 只是order_details
表
id
order_id
product_id
quantity
但是,如果我要創建OrderDetail模型,它將是這樣
public function products()
{
return $this->hasMany(Product::class, 'product_id');
}
public function orders()
{
return $this->hasMany(Order::class, 'order_id');
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.