如何为产品动态属性创建关系?

How to create relationships for product dynamic attributes?

我有 Product 模型,它有属性。在我的例子中,每个产品都可以设置 3 类型的属性:size, color, material。对于每个属性,我都使用模型自定义 table:

型号:

  1. 尺寸
  2. 产品尺寸
  3. 颜色
  4. 产品颜色
  5. Material
  6. 产品Material

现在,如果我想为产品添加新属性,我必须再次创建两个新的 table,例如:

  1. 新属性
  2. 产品新属性

如何通过创建动态属性解决这个问题 table。在我的案例中,每个属性都可以有很多值。我必须使用哪些关系以及有多少 table 可以解决这个问题?

您可以通过使用多对多关系与数据透视字段来解决 3 个表的问题。

属性

| id | name     |
|----|----------|
| 1  | size     |
| 2  | color    |
| 3  | material |

attribute_values

| id | value    | attribute_id|
|----|----------|--------------|
| 1  | S        | 1            |
| 2  | M        | 1            |
| 3  | XL       | 1            |

product_has_attributes

| product_id | attribute_id | attribute_value_id |
|------------|--------------|--------------------|
| 1          | 1            | 1                  |
| 1          | 2            | x                  |
| 1          | 3            | x                  |

所以你的Product模型有一个属性关系

class Product extends Model
{
    public function attributes()
    {
        return $this->belongsToMany('App\Attribute')
            ->withPivot('attribute_value_id')
            ->using('App\ProductAttributes');
    }
}

和您的 Attribute 模型有产品关系

class Attribute extends Model
{
    public function products()
    {
        return $this->belongsToMany('App\Product')
            ->withPivot('value')
            ->using('App\ProductAttributes');
    }
}
class ProductAttribute extends Model
{
    public function value()
    {
        return $this->belongsToMany('App\AttributeValue');
    }
}
@foreach($products as $product)
    @foreach($product->attributes as $attribute)
        echo $attribute->name.' - '.$attribute->pivot->value->value
    @endforeach
@endforeach

https://laravel.com/docs/7.x/eloquent-relationships#many-to-many

编辑 搜索 ProductAttribute 等于值(未经测试的伪代码)

Product::whereHas('attributes.value', function ($query) {
        $query->where('name', 'size')
            ->where('value.value', '');
    })
    ->get();