首页 > 解决方案 > 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?

标签: laraveleloquentfactoryseedinglaravel-8

解决方案


推荐阅读