MartiX's avatar

Seed the table with multiple relationships

Hi guys,

I'm trying to seed my database with multiple relationships, but every time I try to do so, the main model (in this case Car) is created for each additional relation. This is the code:

public function run()
    {
        factory(App\Car::class, 10)->create()->each(function ($car) {
            $car->details()->save(factory(App\CarDetail::class)->make());
            $car->photos()->save(factory(App\Photo::class)->make());
            $car->thumb()->save(factory(App\Thumb::class)->make([
                'thumbable_id' => factory(App\Car::class)->create()->id,
                'thumbable_type' => 'App\Car'
            ]));
            $car->contact()->save(factory(App\Contact::class)->make([
                'contactable_id' => factory(App\Car::class)->create()->id,
                'contactable_type' => 'App\Car'
            ]));
        });
    }

So I want to create only 10 cars with all those 4 relationships so each one of them will have 10 rows as well. But the seeder seeds 40 cars in total, which is not what I intend to do. How to make this working? Thanks.

0 likes
2 replies
tykus's avatar
tykus
Best Answer
Level 104

Twice inside the collection each method you are creating a new Car instance factory(App\Car::class)->create()->id; use $car->id instead.

MartiX's avatar

Gotcha! Thank you @tykus that was the problem I wasn't able to see. :)

Please or to participate in this conversation.