本文介绍了Laravel 5.4如何更新数据透视表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有下一个结构数据透视表:products_equipment_value(id,product_id,equipment_id,value_id).如何更新表字段equipment_id和value_id?

I have next structure pivot table: products_equipment_value(id, product_id, equipment_id, value_id).How to update table fields equipment_id and 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
          ]);
      }

推荐答案

您应该在关系上使用withPivot函数.

You should use withPivot function on the relations.

public function equipments()
{
    return $this->belongsToMany('App\Equipment', 'product_equipment_value')->withPivot('value_id');
}

然后在附加模型时

$product->equipments()
    ->attach([
        $key => ['value_id' =>$val],
    ]);

这篇关于Laravel 5.4如何更新数据透视表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-29 13:15