The last few days I've been rocking my head against the wall with the seeders. I can't seem to get the hang of it.
The relationships are very simple:
A Brand hasMany products and each product belongs to a single brand.
A Category hasMany products and each product belongs to a single category.
Given that, I'm creating 5 categories at the beginning so I can retrieve a random one later.
I'm also creating 10 brands, and for each brand I'm creating 50 products and make them belong to that brand. Then I create the relationship with the product and the category, retrieving a random category for each product.
Im getting this error:
PDOException::("SQLSTATE[HY000]: General error: 1364 Field 'brand_id' doesn't have a default value")
I dont understand why I'm getting this error because I'm creating the relationship prior to creating the products:
$brand->products()->saveMany(factory(App\Product::class, 50).
public function run()
{
$users = factory(\App\User::class, 1000)->create();
$categories = factory(\App\Category::class, 5)->create();
factory(App\Brand::class, 10)->create()->each(function ($brand) {
$brand->products()->saveMany(factory(App\Product::class, 50)->make()->each(function ($product) use ($brand) {
$product->category()->associate($this->getRandomCategory());
$product->save();
}));
});
}
private function getRandomCategory() {
return \App\Category::all()->random();
}
private function getRandomUser() {
return \App\User::all()->random();
}
I don't know if I'm making a big deal out of seeding but it just seems complex to me. Maybe I'm taking a wrong approach using the factories. Is there any great tutorial for seeding out there? Thanks in advance!