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

Suc*_*Man 0 php pivot-table laravel laravel-5.3 laravel-eloquent

我使用 Laravel 5.3

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

表产品:id、名称等

表类别:id、名称等

表 products_categories : id, product_id, category_id

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

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

所以1个产品有很多类别

我的代码是这样的

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

数组 ( ['category1'] => 4 ['category2'] => 11 ['category3'] => 18)

$product_id = 1

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

它用于在数据透视表上添加类别并且它有效

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

我尝试这样:

例如之前这样编辑过的分类

$param['类别'] =

数组 ( ['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]);
}
Run Code Online (Sandbox Code Playgroud)

它没有成功更新字段类别

我该如何解决?

Gab*_*uso 5

尝试使用该sync()功能

Product::find($product_id)->categories()->sync($array_of_categories_id)
Run Code Online (Sandbox Code Playgroud)