mheonyae
mheonyae

Reputation: 643

Laravel seeding many to many tables

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?

Upvotes: 2

Views: 146

Answers (1)

OMR
OMR

Reputation: 12188

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

Upvotes: 1

Related Questions