0

I use Laravel 5.6, and I have a problem with my seeder.

I use this :

factory(\App\Models\Merchant::class)->create([
    'email' => 'admin@domain.com',
])->each(function ($m) {
    $m->stores()->save(factory(\App\Models\Store::class)->create()
        ->each(function ($s) {
            $s->products()->save(factory(\App\Models\Product::class, 10)->create());
        })
    );
});

All are hasMany relations.

Doing this, I have this error :

General error: 1364 Field 'merchant_id' doesn't have a default value (SQL: insert into stores ....)

It's like my first $stores->save( ... ) doesn't use the merchant created.

In my DB, I have one merchant created.

If I use ->make() instead of ->create(), it works for the Store, but I can't save products because it's not persisted...

Is it possible to use multiple save in factories like this ?

Karl Hill
  • 12,937
  • 5
  • 58
  • 95
Vincent Decaux
  • 9,857
  • 6
  • 56
  • 84

1 Answers1

2

Your code may need a little refactoring as you may be chaining creation of models incorrectly:

factory(\App\Models\Merchant::class, 2)->create([
    'email' => 'admin@domain.com',
])->each(function ($m) {
    $store = factory(\App\Models\Store::class)->create(['merchent_id' => $m->id]);
    factory(\App\Models\Product::class, 10)->create(['store_id' -> $store->id]);
    );
});

Note: In order to use the ->each() method, you need to have a collection instance. I do not think creating only one merchant will return a collection. In the example, we create 2 merchents.

thisiskelvin
  • 4,136
  • 1
  • 10
  • 17