简体   繁体   English

Laravel Eloquent:产品、属性和属性值关系

[英]Laravel Eloquent: Product, Attributes and Attribute Values Relationship

I've a scenario for product and attributes relationship.我有一个产品和属性关系的场景。

Models:楷模:

  1. Product (table: products )产品(表:产品
  2. Attributes (table: attributes )属性(表:属性
  3. Attribute Values (table: attribute_values , foreign key: attribute_id )属性值(表: attribute_values ,外键: attribute_id

A product can have multiple attributes so this will be easy with many to many relation b/w product and attributes一个产品可以有多个属性,所以这将很容易与多对多关系 b/w 产品和属性

Model: Attribute Model:属性

<?php

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

Model: Product Model:产品

class Product extends Model{
    public function attributes()
    {
       return $this->belongsToMany(Attribute::class);
    }
}

but, when assigning an attribute to an item user can opt out one of the attribute value from attribute_values ie, the values assigned to an attribute.但是,当将属性分配给项目时,用户可以从attribute_values中选择退出属性值之一,即分配给属性的值。

how can I manage this in eloquent way?如何以 eloquent 方式管理这个?

在此处输入图像描述 I have designed a database schema, is that true?我设计了一个数据库模式,是真的吗?

In this case I would create a Pivot between products and attribute_values, and than you can use it the "Eloquent way" like this:在这种情况下,我将在产品和属性值之间创建一个 Pivot,然后您可以像这样使用“雄辩的方式”:

$products->sync(AttributeValues::where('attribute_id',$attribute_id);

and then if you want to detach a single attribute_value you can detach it using its instance然后如果你想分离单个attribute_value,你可以使用它的实例分离它

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM