如何在 Laravel 8 中定义产品和订单之间的多对多关系

How to define many to many relationship between products and orders in Laravel 8

我有一个 Order_product table 这样的:

id
order_id
product_id

和一个 产品 table 像这样:

id
name
slug
price

如何使用 OrderProduct::where('order_id') 从产品 table 中获取产品名称并将其显示出来以供查看?
以及如何设置关系?

有人可以解释一下以供学习吗?

在您的订单模型中创建函数

public function products() {
     return $this->belongsToMany(Product::class); 
}

*在您看来blade *

foreach($order->products as $product) {
    echo $product->name;
}

It is basically called many to many relationship. The table which has both order_id and product_id is known as pivot table.

您可以在 Laravel 官方文档中找到有关关系的大量文档。 https://laravel.com/docs/8.x/eloquent-relationships。为了您的理解,您可以定义如下关系。

订购型号:

public function products()
{
    return $this->belongsToMany(Product::class);
}

产品型号中:

public function orders()
{
    return $this->belongsToMany(Order::class);
}

在控制器中

use App\Models\Product;

$products = Product::find(1);

foreach ($products->orders as $product) {
    //
}

过滤关系

$product = Product::where('products.id', 1)
    ->with(['orders' => function($query) {
        // Order where condition goes here
        $query->where('orders.id', 1);
    }])
    ->first();

$product = Product::find(1)
    ->with(['orders' => function($query) {
        // Order where condition goes here
        $query->where('orders.id', 1);
    }]);