How can I update pivot table on laravel?

99封情书 提交于 2020-01-10 06:06:06

问题


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:


Try to use the sync() function

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


来源:https://stackoverflow.com/questions/44519339/how-can-i-update-pivot-table-on-laravel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!