2

So i have two tables with many to many relationship so i use a "link" table where is store their id's to connect them.

ExerciseFactory:

$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(),
    ];
});

Section Seeder:

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

ExerciseSeeder:

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

How can i connect random exercises with random sections? Do i need a sepparate Factory/Seeder or can i just somehow loop in the exercise seeder? Since Exercises are generated as last?

mheonyae
  • 581
  • 2
  • 8
  • 24

1 Answers1

1

thanks to this answer

you can do it this way:

after seeding sections and exercises:

  $sections = App\Section::all();

  App\Exercise::all()->each(function ($exercise) use ($sections) {
        $exercise->sections()->attach(
            $sections->random(rand(1, 3))->pluck('id')->toArray()
        );
    });
OMR
  • 11,736
  • 5
  • 20
  • 35