Php 如何在laravel上更新透视表?
我使用的是laravel 5.3 我有3个表格:表格产品、表格类别和表格产品 表产品:id、名称等 表类别:id、名称等 表产品类别:id、产品id、类别id 在模型产品中,我有以下方法:Php 如何在laravel上更新透视表?,php,laravel,laravel-5.3,pivot-table,laravel-eloquent,Php,Laravel,Laravel 5.3,Pivot Table,Laravel Eloquent,我使用的是laravel 5.3 我有3个表格:表格产品、表格类别和表格产品 表产品:id、名称等 表类别:id、名称等 表产品类别:id、产品id、类别id 在模型产品中,我有以下方法: public function categories() { return $this->belongsToMany(Category::class, 'products_categories', 'product_id', 'category_id') ->
public function categories()
{
return $this->belongsToMany(Category::class, 'products_categories', 'product_id', 'category_id')
->withPivot('id')
->withTimestamps();
}
所以1产品有很多种类
我的代码是这样的
例如$param['category']如下所示:
foreach ($param['category'] as $category) {
Product::find($product_id)
->categories()
->wherePivot('product_id', $product_id)
->updateExistingPivot($category, ['category_id' => $category]);
}
排列(
['category1']=>4
['category2']=>11
[‘类别3']=>18)
$product\U id=1
它用于在数据透视表上添加类别,并且可以正常工作
但如果我在透视表上更新category,它将不起作用
我试着这样:
foreach ($param['category'] as $category) {
Product::find($product_id)
->categories()
->wherePivot('product_id', $product_id)
->updateExistingPivot($category, ['category_id' => $category]);
}
例如,以前像这样编辑的类别
$param['category']=
排列(
['category1']=>5
['category2']=>12
[‘类别3']=>19)
$product\U id=1
更新数据透视表数据的代码如下:
foreach ($param['category'] as $category) {
Product::find($product_id)
->categories()
->wherePivot('product_id', $product_id)
->updateExistingPivot($category, ['category_id' => $category]);
}
未成功更新字段类别
我如何解决它?试着使用
尝试使用
@加布里埃尔·卡鲁索,你的回答似乎正确。它似乎也不使用循环。我会再确认一次。顺便说一句,我想问一下。您认为我的代码如何添加数据。我使用循环来添加类别。它不需要使用循环吗?@Amit Gupta,是的,答案似乎是正确的。但我会再次确认。顺便问一下,你认为我的代码如何添加数据?这是真的吗?我使用loop添加itLoop并不总是最好的方法。想象一下你的产品有1000个类别,1000个循环?不数据库(如MySQL)允许您访问,而
sync()
函数使用此功能!你不需要在这里使用循环。@Gabriel Caruso,太好了。我使用这个:Product::find($Product_id)->categories()->sync($param['category'])代码>要添加和更新类别,它可以工作。谢谢lot@Gabriel卡鲁索,你的回答似乎正确。它似乎也不使用循环。我会再确认一次。顺便说一句,我想问一下。您认为我的代码如何添加数据。我使用循环来添加类别。它不需要使用循环吗?@Amit Gupta,是的,答案似乎是正确的。但我会再次确认。顺便问一下,你认为我的代码如何添加数据?这是真的吗?我使用loop添加itLoop并不总是最好的方法。想象一下你的产品有1000个类别,1000个循环?不数据库(如MySQL)允许您访问,而sync()
函数使用此功能!你不需要在这里使用循环。@Gabriel Caruso,太好了。我使用这个:Product::find($Product_id)->categories()->sync($param['category'])代码>要添加和更新类别,它可以工作。谢谢