【问题标题】:Laravel 5.5 - Updating a pivot table with a custom field given two input arraysLaravel 5.5 - 使用给定两个输入数组的自定义字段更新数据透视表
【发布时间】:2018-03-26 17:31:11
【问题描述】:

我有 2 个输入数组,一个用于配料,另一个用于关联食谱所需的成分的数量。我的数据透视表有四列 - idrecipe_idingredient_idamount。我想使用sync 方法更新数据透视表,但是我不知道如何传递第二个“金额”数组值并确保它们与正确的记录同步?

    $ingredients = $request->ingredients;
    $ingredientAmounts = $request->ingredients_amount;

    $project->ingredients()->sync( $ingredients => ['amount' => $ingredientAmounts] );

成分及其数量都有相同的键,所以我想我可以手动循环它们并更新数据透视表,但我觉得会有一种更简单的方法可以更好地利用 eloquent。

【问题讨论】:

    标签: arrays input eloquent pivot-table laravel-5.5


    【解决方案1】:

    两个输入数组需要合并成所需的格式:

    $user->roles()->sync([1 => ['expires' => true], 2, 3]);

    来自https://laravel.com/docs/5.5/eloquent-relationships#updating-many-to-many-relationships

        $array = [];
    
        foreach ($ingredients as $key => $ingredient) {
            $array[$ingredient->id] = ['amount' => $ingredientAmounts[$key]];
        }
    
        $project->ingredients()->sync($array);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-19
      • 1970-01-01
      • 2018-04-04
      • 2019-02-09
      • 1970-01-01
      相关资源
      最近更新 更多