【问题标题】:Many to Many relationship Laravel with different Values, products attributes多对多关系 Laravel 与不同的值、产品属性
【发布时间】:2020-02-18 02:38:13
【问题描述】:

我需要创建具有多对多关系的产品属性,但属性值有问题。例如:

Product->belongsToMany(App\Attribute) Attribute->belongsToMany(App\Product)

现在我需要属性为“颜色”,并且我希望该颜色为“红色”并从另一个表中获取。

所以我不知道如何建立这种关系。

Product->attributes->Color->red.

事实上,如果我这样做,它会起作用,但当然所有产品都会采用该属性值“红色”,所以所有产品都会变成红色,这是不正确的。

我尝试过并且效果很好的简单方法是没有数据透视表和简单的关系。 刚刚在产品表中添加了一个包含属性名称和值的列,但是这样做会将我的产品表转换为一个包含很多属性的巨型表,例如:

'name', 'description', 'price', 'color', 'size', 'warranty' and so on with too many attributes which is really unoptimized

预期结果是产品具有多个属性,而这些属性具有不同产品的多个值。 希望有人可以解决这个关系问题或启发我。反正比你好。

【问题讨论】:

  • 您似乎正在尝试做一些类似于 Wordpress 分类的事情,不是吗?如果是这样,您的 Attribute 表将只有两个字段“name”和“value.name = 'color' value = 'red' 然后获取 $product->attributes 将返回一个名称/值对列表。你必须在产品上创建自己的助手/函数以获取指定的属性,如“颜色”(如果指定产品存在)

标签: mysql laravel


【解决方案1】:

模型产品

public function attributes()
    {
        return $this->belongsToMany(Attribute::class, 'product_attributes', 'product_id', 'attribute_id');
    }

模特入驻

public function products()
    {
        return $this->belongsToMany(Product::class, 'product_attributes', 'attribute_id', 'product_id');
    }

代码

$product = new Product();
$attributes = $product->attributes;
$productWithAttributes = $product->with('attributes')->get();

【讨论】:

    猜你喜欢
    • 2020-09-07
    • 2017-11-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-16
    • 2012-10-27
    • 2022-10-25
    相关资源
    最近更新 更多