如何在 Laravel 8 中使用不同的数据透视数据建立多个多对多关系?

the*_*ier 6 factory seeding laravel laravel-8

我知道我可以使用该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 流畅的工厂方法。

cba*_*ier 12

当您调用这样的方法时,会在调用之前method(rand(1,100))对其进行评估。rand这将与做的一样method(59)

幸运的是,Laravel 允许您使用回调来重新评估每次调用的参数,

Meal::factory()
        ->count(3)
        ->hasAttached(Ingredient::factory()->count(3), fn => ['gram' => rand(1,100)])
        ->create();
Run Code Online (Sandbox Code Playgroud)

如果您使用低于 7.4 的 PHP 版本,您将无法使用箭头函数,您必须这样做

Meal::factory()
        ->count(3)
        ->hasAttached(Ingredient::factory()->count(3), function () { 
            return ['gram' => rand(1,100)]; 
        })
        ->create();
Run Code Online (Sandbox Code Playgroud)