首页 文章

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

提问于
浏览
0

我用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'] => 5 ['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 回答

  • 3

    尝试使用sync() function

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

相关问题