I'm trying to seed my database with faker, but I have some issues with a foreign element. I have one and only user and I don't know its id. I want all the posts to have its id.
This is how I did this :
public function run()
{
factory(App\User::class)->create();
factory(App\Category::class, 3)->create();
$user = \App\User::first();
factory(App\Post::class, 10)->create(['author_id' => $user->id]);
}
And this is my post factory :
$factory->define(App\Post::class, function (Faker\Generator $faker) {
return [
'title' => $faker->unique()->sentence(5),
'subtitle' => $faker->optional()->sentence(10),
'markdown' => $faker->text(500),
'draft' => $faker->boolean(),
'category_id' => $faker->numberBetween(1, 6),
];
});
After a db:seed
, this is the error I get (users and categories are well populated) :
SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`laman`.`posts`, CO
NSTRAINT `posts_author_id_foreign` FOREIGN KEY (`author_id`) REFERENCES `users` (`id`)) (SQL: insert into `posts` (`title`, `slug`, `subtit
le`, `markdown`, `draft`, `category_id`, `author_id`, `html`, `published_at`, `updated_at`, `created_at`) values (title.,
slug, , markdown, 0, 6, 1, html, 2017-04-25 20:08:34, 2017-04-25 20:08:34, 2017-04-25
20:08:34))
Here the user id is 1 or it should be 9. Why?