[英]Laravel merge result of two relationships that point to one table
我有一個orders_products
表。 對於一對多關系。 一個訂單可以有多個產品。 每個許可證對於訂購的產品都是獨一無二的。 因為每個許可證都是為該給定產品唯一生成的。
orders_products
表有一個訂單 ID、一個 product_id 和一個 license_id。 這是因為所有訂單都有相關產品和相關許可證。
在Order
模型中,我有以下關系:
class Order extends Model {
public function products()
{
return $this->belongsToMany(Product::class, 'orders_products', 'order_id', 'product_id');
}
public function licenses()
{
return $this->belongsToMany(License::class, 'orders_products', 'license_id');
}
}
但現在我希望許可證顯示在產品對象中。 因為它們是相關的。 那么這些關系需要以某種方式合並嗎?
檢索數據時:
$data = Order::with('products', 'licenses')->get();
結果不完整:
"data": [
{
"id": 1, <!-- id of the orders table
"user_id": "2",
"products": [
{
"id": 1,
"name": "Product 1",
"price": "100.0",
"license": null <-- here I would like to licenses relation to kick in
},
{
"id": 2,
"name": "Product 2",
"price": "100.0",
"license": null
}
],
"payed_at": "2020-02-21 17:07:49",
"payed": true
}
]
}
如您所見,產品數據以正確的方式填充。 但是許可證是單獨附加的。 但它們需要成為產品的一部分。
那么如何合並order_products
表中product_id和license_id列的結果呢?
更新:
我認為解決方案在某種程度上在於在產品模型上調用 license() 。
"products": [
{
"id": 1,
"name": "Developer Forms Plugin",
"price": "100.0",
"license": {
"id": null,
"license": null,
"slots": null
}
}]
輸出應該是怎樣的。 該許可證對每個訂購的產品都是唯一的。 僅僅擁有每個產品的許可證是不夠的。 它們是為每個訂購的產品生成的。
我認為你需要這樣的東西:
$data = Order::with('products.license')->get();
這樣我們就可以獲得與產品相關的許可。 我稱之為 license 是因為你描述了它們之間的一對一關系,所以我假設你是用單數寫的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.