Laravel 5.5 - 使用给定两个输入数组的自定义字段更新数据透视表 table
Laravel 5.5 - Updating a pivot table with a custom field given two input arrays
我有 2 个输入数组,一个用于 ingredients,另一个用于相关食谱所需的 amount 成分。我的数据透视表 table 有四列 - id
、recipe_id
、ingredient_id
和 amount
。我想使用 sync
方法更新数据透视表 table,但是我不知道如何传递第二个 'amounts' 数组值并确保它们与记录正确?
$ingredients = $request->ingredients;
$ingredientAmounts = $request->ingredients_amount;
$project->ingredients()->sync( $ingredients => ['amount' => $ingredientAmounts] );
成分及其数量都有相同的键,所以我想我可以手动遍历它们并更新数据透视表 table,但我觉得会有一种更简单的方法可以更好地使用eloquent.
需要将两个输入数组合并为所需的格式:
$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);
我有 2 个输入数组,一个用于 ingredients,另一个用于相关食谱所需的 amount 成分。我的数据透视表 table 有四列 - id
、recipe_id
、ingredient_id
和 amount
。我想使用 sync
方法更新数据透视表 table,但是我不知道如何传递第二个 'amounts' 数组值并确保它们与记录正确?
$ingredients = $request->ingredients;
$ingredientAmounts = $request->ingredients_amount;
$project->ingredients()->sync( $ingredients => ['amount' => $ingredientAmounts] );
成分及其数量都有相同的键,所以我想我可以手动遍历它们并更新数据透视表 table,但我觉得会有一种更简单的方法可以更好地使用eloquent.
需要将两个输入数组合并为所需的格式:
$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);