简体   繁体   中英

Laravel merge result of two relationships that point to one table

I have an orders_products table. For a one-to-many relationship. One order can have multiple products. And every license is unique to an ordered product. Because every license is uniquely generated for that given product.

The orders_products table has an order ID and a product_id and a license_id. This is because all orders have a related product and a related license.

在此处输入图片说明

In the Order model I have these relationships:

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');
}
}

But now I would like the licenses to show up in the product objects. Because they are related. So somehow these relationships need to be merged?

When retrieving the data:

$data = Order::with('products', 'licenses')->get();

The result is incomplete:

"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
    }
]

}

As you can see the product data gets populated the right way. But the licenses get attached separately. But they need to be part of a product.

So how to merge the results of the columns product_id and license_id from the table order_products table?

Update:

I think the solution somehow lies in calling license() on the Product model.

"products": [
            {
                "id": 1,
                "name": "Developer Forms Plugin",
                "price": "100.0",
                "license": {
                    "id": null,
                    "license": null,
                    "slots": null
                }
            }]

Is how the output should be. The license being unique to every ordered product. Just having a license for each product is not enough. They are generated for every ordered product.

I think you need something like :

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

This way we can get the license related to the products. I called license because you described a one to one relation between them, so I assumed that you wrote it in singular.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM