如何在laravel上更新数据透视表?

时间:2017-06-13 10:46:36

标签: php laravel laravel-5.3 pivot-table laravel-eloquent

我使用laravel 5.3

我有3个表:表产品,表类别和表products_categories

表产品:id,name等

表类别:id,name等

table products_categories:id,product_id,category_id

在模型产品中,我有这样的方法:

public function categories()
{
    return $this->belongsToMany(Category::class, 'products_categories', 'product_id', 'category_id')
                ->withPivot('id')
                ->withTimestamps();
}

所以1个产品有很多类别

我的代码就像这样

例如$ param [' category']就像这样:

  

阵列(       [' category1'] => 4       [' category2'] => 11       [' category3'] => 18)

     

$ product_id = 1

foreach ($param['category'] as $category) {
    Product::find($product_id)
        ->categories()
        ->attach(
            $category, 
            []
        );
}

它曾用于在数据透视表上添加类别并且可以正常工作

但是如果我在数据透视表上更新类别,它就不起作用

我试着这样:

例如,之前编辑过的类别

$ param [' category'] =

  

阵列(       [' category1'] =>五       [' category2'] => 12       [' category3'] => 19)

     

$ product_id = 1

更新数据透视表上的数据的代码如下:

foreach ($param['category'] as $category) {
    Product::find($product_id)
           ->categories()
           ->wherePivot('product_id', $product_id)
           ->updateExistingPivot($category, ['category_id' => $category]);
}

它没有成功更新字段类别

我该如何解决?

1 个答案:

答案 0 :(得分:3)

尝试使用sync() function

Product::find($product_id)->categories()->sync($array_of_categories_id)