【问题标题】:Laravel merge result of two relationships that point to one tableLaravel 合并指向一个表的两个关系的结果
【发布时间】: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
                }
            }]

输出应该是怎样的。每个订购的产品的许可证都是唯一的。仅仅拥有每个产品的许可证是不够的。它们是为每个订购的产品生成的。

【问题讨论】:

    标签: php laravel eloquent


    【解决方案1】:

    我认为你需要类似的东西:

    $data = Order::with('products.license')->get();
    

    这样我们可以获得与产品相关的许可证。我之所以称为许可证,是因为您描述了它们之间的一对一关系,所以我假设您以单数形式编写它。

    【讨论】:

    • 我认为这将导致产品具有 1 个许可证。但事实并非如此。产品的每个订单都需要拥有唯一的许可证。
    • 所以每个订单都有一个许可证和许多产品?对我来说,您在代码示例中指出的方式告诉您需要 "license": null 成为产品许可证一对一关系中的对象。我发布的代码是“但现在我希望许可证显示在产品对象中。因为它们是相关的。所以这些关系需要以某种方式合并?”您问题的一部分。
    • Order::with('products.license')-&gt;get();订单中获取所有订单并用('products.license')获取订单内的所有产品,然后获取与产品相关的许可证。如果您的订单有 10 种产品,那么这些产品中的每一种都将获得相关许可证及其中的每个字段。
    猜你喜欢
    • 2014-01-19
    • 2018-12-11
    • 1970-01-01
    • 2017-08-15
    • 2022-09-28
    • 1970-01-01
    • 2018-04-04
    • 2013-07-25
    • 1970-01-01
    相关资源
    最近更新 更多