我知道我可以使用该hasAttached
方法在 Laravel 8 中创建与数据透视表数据的多对多关系:
Meal::factory()
->count(3)
->hasAttached(Ingredient::factory()->count(3), ['gram' => 100])
->create();
Run Code Online (Sandbox Code Playgroud)
是否有任何方便的方法(除了编写自定义 for 循环之外)为数据透视表中的每个附加条目添加随机数据?我希望'gram'
是每个创建的关系的随机数。我尝试了以下方法,但rand
表达式仅被计算一次,并为每个关系使用相同的条目填充数据透视表:
Meal::factory()
->count(3)
->hasAttached(Ingredient::factory()->count(3), ['gram' => rand(1,100]) //not working
->create();
Run Code Online (Sandbox Code Playgroud)
编辑:我基本上想要实现
for ($i = 1; $i <= 3; $i++) {
$meal = Meal::factory()->create();
for ($j = 1; $j <= 3; $j++) {
$ingredient = Ingredient::factory()->create();
$meal->ingredients()->save($ingredient, ['gram' => rand(5, 250)]);
}
}
Run Code Online (Sandbox Code Playgroud)
使用 Laravel 流畅的工厂方法。