How can I update pivot table on laravel?

2020-02-15 22:55发布

I use laravel 5.3

I have 3 table : table product, table category and table products_categories

table product : id, name, etc

table category : id, name, etc

table products_categories : id, product_id, category_id

In model product, I have method this :

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

So 1 product have many category

My code like this

For example $param['category'] like this :

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

$product_id = 1

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

It used to add category on the pivot table and it works

But if I update category on the pivot table, it does not work

I try like this :

For example the category previously edited like this

$param['category'] =

Array ( ['category1'] => 5 ['category2'] => 12 ['category3'] => 19 )

$product_id = 1

And the code to update data on the pivot table like this :

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

It did not update the field category successfully

How can I solve it?

1条回答
啃猪蹄的小仙女
2楼-- · 2020-02-16 00:00

Try to use the sync() function

Product::find($product_id)->categories()->sync($array_of_categories_id)
查看更多
登录 后发表回答