【问题标题】:How to seed multiple many-to-many relationships with different pivot data in laravel 8?如何在 laravel 8 中使用不同的数据透视数据播种多个多对多关系?
【发布时间】: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 流畅的工厂方法。

【问题讨论】:

  • 我现在没有任何可以尝试的东西,但这行得通吗? -&gt;hasAttached(Ingredient::factory()-&gt;count(3), fn() =&gt; ['gram' =&gt; rand(1,100])
  • @ClémentBaconnier 确实如此!非常感谢。您可能想将其发布为答案,我会接受。

标签: laravel factory seeding laravel-8


【解决方案1】:

当您调用类似method(rand(1,100)) 的方法时,rand 在调用之前被评估。这将与method(59) 相同

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

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

如果你使用 7.4 以下的 PHP 版本,你将无法使用箭头功能,你必须这样做

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

【讨论】:

    猜你喜欢
    • 2021-05-08
    • 1970-01-01
    • 2023-02-05
    • 2014-12-07
    • 2018-09-23
    • 2021-05-31
    • 2014-06-13
    • 2021-04-28
    • 2020-07-03
    相关资源
    最近更新 更多