【问题标题】:Laravel seeding many to many tablesLaravel 播种多对多表
【发布时间】:2020-11-05 06:31:27
【问题描述】:

所以我有两个具有多对多关系的表,所以我使用一个“链接”表来存储它们的 id 来连接它们。

运动工厂:

$factory->define(Exercise::class, function (Faker $faker) {
    return [
        'name' => $faker->name(),
        'description' => $faker->sentence(),
        'duration' => $faker->numberBetween(1,20),
        'duration_unit' => 'Reps'
    ];
});

SectionFactory:

$factory->define(Section::class, function (Faker $faker) {
    return [
        'routine_id' => function(){
            return Routine::all()->random();
        },
        'name' => $faker->word,
        'description' => $faker->sentence(),
    ];
});

部分播种器:

public function run()
{
    factory(App\Section::class,40)->create();
}

ExerciseSeeder:

public function run()
{
    factory(App\Exercise::class,120)->create();
}

如何将随机练习与随机部分联系起来?我需要一个单独的工厂/播种机还是我可以以某种方式循环在练习播种机中?由于练习是最后生成的?

【问题讨论】:

    标签: laravel


    【解决方案1】:

    感谢answer

    你可以这样做:

    在播种部分和练习之后:

      $sections = App\Section::all();
    
      App\Exercise::all()->each(function ($exercise) use ($sections) {
            $exercise->sections()->attach(
                $sections->random(rand(1, 3))->pluck('id')->toArray()
            );
        });
    

    【讨论】:

      猜你喜欢
      • 2017-12-29
      • 2019-11-17
      • 2021-10-29
      • 2019-01-05
      • 2021-05-08
      • 2020-10-08
      • 1970-01-01
      • 2015-04-20
      • 2020-01-21
      相关资源
      最近更新 更多