【发布时间】:2020-02-21 17:59:13
【问题描述】:
我有一个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列的结果呢?
更新:
我认为解决方案在于在 Product 模型上调用 license()。
"products": [
{
"id": 1,
"name": "Developer Forms Plugin",
"price": "100.0",
"license": {
"id": null,
"license": null,
"slots": null
}
}]
输出应该是怎样的。每个订购的产品的许可证都是唯一的。仅仅拥有每个产品的许可证是不够的。它们是为每个订购的产品生成的。
【问题讨论】: