【问题标题】:How can I update pivot table on laravel?如何更新 laravel 上的数据透视表?
【发布时间】: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


    【解决方案1】:

    尝试使用sync() function

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

    【讨论】:

    • @Gabriel Caruso,您的回答似乎是正确的。似乎它也不使用循环。我会再次确认。顺便说一句,我想问。你觉得我的代码如何添加数据。我使用循环来添加类别。不用循环吗?
    • @Amit Gupta,是的,答案似乎正确。但我会再次确认。顺便说一句,您认为我的代码如何添加数据?真的吗?我使用循环添加它
    • 循环并不总是最好的方法。您的产品有 1.000 个类别、1.000 个循环的图像?不!数据库(如 MySQL)允许您使用 batch insert,而 sync() 函数使用此功能!
    • 这里不需要使用循环。
    • @Gabriel Caruso,太好了。我用这个:Product::find($product_id)->categories()->sync($param['category']); 添加和更新类别,它有效。非常感谢
    猜你喜欢
    • 2018-02-26
    • 1970-01-01
    • 2016-03-09
    • 1970-01-01
    • 1970-01-01
    • 2021-10-03
    • 1970-01-01
    • 1970-01-01
    • 2017-07-01
    相关资源
    最近更新 更多