我想使用faker播種我的數據庫,但是我有一些異常元素的問題。我有一個用戶,但我不知道它的ID。我希望所有帖子都有它的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.爲什麼?
看起來這樣每次都會創建一個新用戶,但是您正在調用表中的第一個用戶。是這種情況,還是你刷新你的遷移? – Naltroc
我刪除用戶和類別un phpmyadmin。有沒有更好的方式來截斷與關係表? – Wizix
使用'php artisan migrate:refresh --seed'將完全回滾並遷移數據庫以及填充播種器文件。只要你在數據庫中沒有有價值的數據,這就很好。 一般而言,使用遷移來管理數據庫是一種很好的做法,儘管我已經發現自己會每隔一段時間手動刪除一次。 – Naltroc