我有下一个结构数据透视表:products_equipment_value(id,product_id,equipment_id,value_id)。如何更新表字段equipment_id和value_id?
public function equipments()
{
return $this->belongsToMany('App\Equipment', ' product_equipment_value');
}
public function values()
{
return $this->belongsToMany('App\Value', ' product_equipment_value', 'product_id', 'value_id')
}
使用(不工作)
$product->equipments()->detach();
foreach($data['eq'] as $key => $val){
$product->equipments()->attach([
'equipment_id' => $key,
'value_id' =>$val
]);
}
答案 0 :(得分:1)
您应该在关系上使用withPivot
函数。
public function equipments()
{
return $this->belongsToMany('App\Equipment', 'product_equipment_value')->withPivot('value_id');
}
然后当你附上模特
$product->equipments()
->attach([
$key => ['value_id' =>$val],
]);
答案 1 :(得分:1)
参考多对多Eloquent的关系(https://laravel.com/docs/5.5/eloquent-relationships#many-to-many),您可以同步ID:
$product->equipments()->sync([array_of_equipments_ids]);
示例:
$product->equipments()->sync([3, 8, 9, 24]);
如果您定义了“多对多”反转关系,您也可以通过设备实例执行此操作:
$equipment->values()->sync([array_of_values_ids]);
如果您的数据透视表有额外的列,您可以像这样添加它们:
public function equipments(){
return $this->belongsToMany('App\Equipment', 'product_equipment_value')->withPivot('extra_column1');
}
所以:
$product->equipments()->sync([1 => ['extra_column1' => 'Value for this column']])
请注意,您可以使用sync()或attach()方法构建多对多关联。你可以看看这里:https://stackoverflow.com/a/23969879/8620746