問題描述
我使用 Laravel 5.3
I use laravel 5.3
我有 3 個表:表產品、表類別和表 products_categories
I have 3 table : table product, table category and table products_categories
表產品:id、名稱等
表格類別:id、名稱等
table category : id, name, etc
表 products_categories : id, product_id, category_id
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();
}
所以 1 個產品有多個類別
So 1 product have many category
我的代碼是這樣的
例如 $param['category'] 像這樣:
For example $param['category'] like this :
數組 (['category1'] => 4['category2'] => 11['category3'] => 18 )
Array ( ['category1'] => 4 ['category2'] => 11 ['category3'] => 18 )
$product_id = 1
$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
我是這樣嘗試的:
比如之前這樣編輯過的分類
For example the category previously edited like this
$param['category'] =
$param['category'] =
數組 (['category1'] => 5['category2'] => 12['category3'] => 19 )
Array ( ['category1'] => 5 ['category2'] => 12 ['category3'] => 19 )
$product_id = 1
$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]);
}
未成功更新字段類別
我該如何解決?
推薦答案
嘗試使用 sync()
函數
Try to use the sync()
function
Product::find($product_id)->categories()->sync($array_of_categories_id)
這篇關于如何在 Laravel 上更新數據透視表?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!