【发布时间】:2017-11-15 02:30:37
【问题描述】:
我使用 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();
}
所以 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]);
}
没有成功更新字段类别
我该如何解决?
【问题讨论】:
标签: php laravel laravel-5.3 pivot-table laravel-eloquent