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

问题描述

我有一个像这样的 Order_product 表:

id
order_id
product_id

一个 products 表,如下所示:

id
name
slug
price

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

有人可以为学习目的解释一下吗?

解决方法

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

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

*并且在您看来刀片 *

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

基本上称为多对多关系。有的表 order_id 和 product_id 都称为数据透视表。

你可以在 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);
    }]);