我正在尝试使用faker来播放我的数据库,但是我有一些外来元素的问题。我有一个唯一的用户,我不知道它的ID。我希望所有帖子都有自己的身份 这就是我这样做的方式:
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]);
}
这是我的邮局:
$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),
];
});
在db:seed
之后,这是我得到的错误(用户和类别填充得很好):
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))
此处用户ID为1或应为9.为什么?
答案 0 :(得分:0)
我建议按如下方式为您的数据库播种:
要避免手动删除数据库条目,请使用DB::table('YourDBTable')->truncate();
:
public function run()
{
DB::table('user')->truncate();
DB::table('posts')->truncate();
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]);
}
现在每次运行artisan命令db:seed
时,都会截断你的用户表,然后用新数据填充你的数据库,这样你就可以获取单个用户,也可以获取正确的用户。 first()
方法。