【发布时间】:2021-01-25 22:18:55
【问题描述】:
我知道我可以在 Laravel 8 中使用hasAttached 方法来create many-to-many relationships with pivot data:
Meal::factory()
->count(3)
->hasAttached(Ingredient::factory()->count(3), ['gram' => 100])
->create();
是否有任何方便的方式y(除了编写自定义 for 循环)为每个附加条目使用随机数据为数据透视表播种?我想要 @ 987654324@ 是每个已创建关系的随机数。我尝试了以下方法,但 rand 表达式只被评估一次,并为每个关系使用相同的条目填充数据透视表:
Meal::factory()
->count(3)
->hasAttached(Ingredient::factory()->count(3), ['gram' => rand(1,100]) //not working
->create();
编辑:我基本上想实现
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)]);
}
}
使用 Laravel 流畅的工厂方法。
【问题讨论】:
-
我现在没有任何可以尝试的东西,但这行得通吗?
->hasAttached(Ingredient::factory()->count(3), fn() => ['gram' => rand(1,100]) -
@ClémentBaconnier 确实如此!非常感谢。您可能想将其发布为答案,我会接受。
标签: laravel factory seeding laravel-8