Laravel 同步多个关系加上枢轴数据(不包括空数据)
我有一个多对多关系,Recipes
和 Ingredients
。我正在尝试将多个成分
同步到食谱
。我有一个编辑表单,我可以在其中发送食谱
和所有成分
的列表。
在我的 ingredient_recipe
表中,我有两个额外的数据透视列:number1
和 number2
。
在我的表单中,我有两个下拉菜单,简化如下:
<select name="{{ $ingredient->id }}[number1]">
<option></option> // Empty value
<option value="example1">Example 1</option>
<option value="example2">Example 2</option>
</select>
<select name="{{ $ingredient->id }}[number2]">
<option></option> // Empty value
<option value="example1">Example 1</option>
<option value="example2">Example 2</option>
</select>
提交表单时,我得到以下结果:
array:2 [▼
1 => array:2 [▼
"number1" => example1
"number2" => example2
]
2 => array:2 [▼
"number1" => example2
"number2" => example1
]
]
在我的控制器的 update
方法中,我正在执行以下操作以将成分同步到配方:
$recipe->ingredients()->sync($ingredients);
其中 $ingredients
是上面发布的请求的输出。
虽然这确实可以完美地工作,但它也会同步下拉列表中没有选择的值,因为 $ingredient->id
将始终被提交。
关于我如何处理这个问题,我有两个问题。
- 我的主要问题是,如何避免具有空下拉值的成分同步?
- 我认为这似乎是我想要实现的目标的错误解决方案,如果是这样,有任何指向正确方向的指针吗?
I have a many-to-many relation, Recipes
and Ingredients
. I am trying to sync multiple ingredients
to a recipe
. I have an edit form where I send a recipe
and a list of all ingredients
.
In my ingredient_recipe
table I have two extra pivot columns, number1
and number2
.
In my form I have two dropdowns, simplified below:
<select name="{{ $ingredient->id }}[number1]">
<option></option> // Empty value
<option value="example1">Example 1</option>
<option value="example2">Example 2</option>
</select>
<select name="{{ $ingredient->id }}[number2]">
<option></option> // Empty value
<option value="example1">Example 1</option>
<option value="example2">Example 2</option>
</select>
When submitting the form, I get the following results:
array:2 [▼
1 => array:2 [▼
"number1" => example1
"number2" => example2
]
2 => array:2 [▼
"number1" => example2
"number2" => example1
]
]
In my controller's update
method I am doing the following to sync the ingredients to the recipe:
$recipe->ingredients()->sync($ingredients);
Where $ingredients
is the output of the request posted above.
While this does work flawlessly, it also syncs the values that have no selection in the dropdowns, because the $ingredient->id
will always be submitted.
I have two questions about how I am approaching this.
- My main question is, how to avoid that ingredients with empty dropdown values get synced?
- It seems like a wrong solution to what I want to achieve I think, if so, any pointers in the right direction?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我最终做的是以下内容:
这会检查
number1
或number2
是否为空,如果是,它会从数组中删除整个成分,因此只有选定的值会被删除。已同步。What I ended up doing is the following:
This checks if either
number1
ornumber2
is empty and if so, it removes the whole ingredient from the array so only selected values will be synced.