如何在laravel中获取多对多关系数据?

时间:2020-05-02 07:49:42

标签: laravel

Suppliers table

id | name

1  | supplier1

2  | supplier2
Products table

id | name

1  | product1

2  | product2
Attributes table

id | name

1  | width

2  | heigh

3  | weight

4  | volume
supplier_product table

supplier_id | product_id | price

1           | 1          | 1000

1           | 2          | 1500

2           | 1          | 1100
attribute_product

supplier_id | product_id | attribute_id | value

1           | 1          | 1            | 10

1           | 1          | 2            | 15

1           | 1          | 3            | 20

1           | 2          | 1            | 11

1           | 2          | 2            | 16

2           | 1          | 1            | 10

2           | 1          | 2            | 13

如何获取每个供应商的每种产品的属性?

1 个答案:

答案 0 :(得分:0)

只要您修改表的结构,就可以使用hasManyThrough关系(https://laravel.com/docs/7.x/eloquent-relationships#has-many-through)。

供应商模型

public function attributes()
{
    return $this->hasManyThrough('App\Attribute', 'App\Product');
}