laravel - What Is the Correct Way to Seed Multiple Many-to-many Relationships for a Single Instance in Laravel 8?
问题描述
I'm trying to create a model instance which has already more than one many-to-many relationships defined by doing this:
$meal = Meal::factory()
->hasAttached(Ingredient::factory(), ['gram' => 100])
->hasAttached(Ingredient::factory(), ['gram' => 200])
->create();
I end up with one entry to my Meal
table and two entries to the Ingredient
table - which is fine. However, I expected to have also two entries in my pivot table (1x where 'gram' = 100
and 1x where 'gram' = 200
). However, I end up with 3 entries instead.
I'm wondering where the second entry is coming from.
+----+---------------+---------+------+
| id | ingredient_id | meal_id | gram |
+----+---------------+---------+------+
| 1 | 1 | 1 | 100 |
| 2 | 1 | 1 | 200 |
| 3 | 2 | 1 | 200 |
+----+---------------+---------+------+
What is the best way to seed this kind of relationship (preferably in one call using the new factory methods)? Would it make more sense to break the seeding into multiple steps, e.g. create a model first and then attach the relationships?
解决方案
推荐阅读
- json - 为什么对 NESTED 对象的 Kibana 查询返回估计价格?
- http - 如何在 Flutter 移动应用程序的 API 调用中传递基本身份验证凭据?
- python-3.x - Python pandas:如果键在其他列中,如何为新列赋值
- javascript - 如何从 vue js 中的组件渲染组件
- reactjs - 在“create-react-app”应用程序中使用 Enzyme 对 React/Redux 进行单元测试
- c# - 如何在没有 vs 的情况下在 C# 7 中编译 asp.net mvc 5
- birt - 如何检测Birt中的动态文本溢出
- linux-kernel - /proc/$pid/maps 中的“已删除”是什么意思?
- linux - 加载共享库时出错:libevent-2.0.so.5
- authentication - 如何在 VSTS 的特定帐户下运行 vstest?