2017-06-29 86 views
4

我使用多对多的关系。我想为这个属性设置两个值。Laravel多对多

产品,

属性,

attribute_product =>product_id,attribute_id,value

enter image description here

我知道这是错的,但我想告诉你,我想

$product->attributes()->sync([ 
      1 => [ 
       'value' => 'sky' 
      ], 
      1 => [ 
       'value' => 'night' 
      ], 
     ]); 

更新2

Schema::create('attribute_product', function (Blueprint $table) { 

$table->unsignedInteger('product_id'); 
$table->unsignedInteger('attribute_id'); 
$table->text('value')->nullable(); 
$table->integer('devalue_id')->nullable(); // value id 

$table->primary(['product_id', 'attribute_id', 'devalue_id']); 

}); 

更新1

我需要设置的天空,晚上

product_id attribute_id  value  devalue_id 
1   1     sky   1 
1   1     night  2 
... 
+1

请您重新说明一下吗? –

+0

@ImAtWar https://www.digikala.com/Product/DKP-149283此笔记本电脑具有多个attributs值: –

+0

用法:多媒体,窄和光。它如何保存这个值 –

回答

1

我不是100%肯定,你想要做的,所以我会解决两种不同的情况。

1:创建一个属性并将其链接到产品。在这种情况下,您有一个产品并知道属性的名称,但它尚未存在于您的属性表中。它看起来像这样:

$product->attributes()->saveMany([ 
    new App\Attribute(['title' => 'sky']), 
    new App\Attribute(['title' => 'night']), 
]); 

2:将现有属性附加到产品。在这种情况下,您的属性表中已经有属性并查看了它。实际上,它非常相似,除了找到属性。

$attribute1 = Attributes::where('title', 'sky')->first(); 
$attribute2 = Attributes::where('title', 'night')->first(); 

$product->attributes()->saveMany([ 
    $attribute1, 
    $attribute2, 
]); 
+0

$ product-> attributes() - > detach(); $ product-> attributes() - > attach([...]);我现在正在做这个 –

+0

而不是先做分离,你实际上可以使用$ product-> sync([...]),它将摆脱不在数组中的任何属性,并添加任何是。代码中有点整齐。 :) – llhilton

+0

同步不适用于** 3主键*** –

2

这样的事情,我可以看到2个选项:

手动安装和拆卸所需的记录。这可能会导致检索数据时出现问题,因为它会返回多个相同的属性,但是,您可能会在集合上使用groupBy来解决此问题(如果它是针对您的)。

2.

你可以在枢轴表中的值列中存储一个JSON对象。这将允许您为同一个属性拥有多个值。要做到这一点,你可以创建一个AttributeProductPivot类(或任何你想将它命名),扩展Illuminate\Database\Eloquent\Relations\Pivot并添加蒙上属性,它即:

class AttributeProductPivot extends \Illuminate\Database\Eloquent\Relations\Pivot 
{ 
    /** 
    * The attributes that should be casted to native types. 
    * 
    * @var array 
    */ 
    protected $casts = [ 
     'value' => 'collection', //or object or array 
    ]; 

} 

然后改变你的attributes()关系是:

public function attributes() 
{ 
    return $this->belongsToMany(Attribute::class) 
     ->using(AttributeProductPivot::class) 
     ->withPivot('value'); 
} 

using()允许你设置一个不同的Pivot Model,它是默认的。如果需要,不要忘记对相反的关系做同样的事情。

在附加/同步时,您需要自己将value属性强制转换为json。

希望这会有所帮助!

+0

你的意思是在夜间像json一样保存天空? –

+0

{“Sky”,“Night”} mysql是否容易搜索值?获取属性为天空的帖子 –

+0

我应该如何处理我的主键 - 2/3? –