假数据生成不满足约束:无法 db:seed / migrate:refresh --seed 的一种情况
我的报错信息是:
/v/w/larabbs (master)> php artisan db:seed
Seeding: Database\Seeders\UsersTableSeeder
Seeded: Database\Seeders\UsersTableSeeder (232.88ms)
Seeding: Database\Seeders\TopicsTableSeeder
Seeded: Database\Seeders\TopicsTableSeeder (382.83ms)
Seeding: Database\Seeders\RepliesTableSeeder
Illuminate\Database\QueryException
SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`larabbs`.`replies`, CONSTRAINT `replies_topic_id_foreign` FOREIGN KEY (`topic_id`) REFERENCES `topics` (`id`) ON DELETE CASCADE) (SQL: insert into `replies` (`content`, `topic_id`, `user_id`, `updated_at`, `created_at`) values (<p>Facilis repellat qui et accusamus aliquam et.</p>, 97, 5, 2021-03-10 17:57:51, 2021-03-10 17:57:51))
检查后,发现是我的 factory 写的无法满足约束条件
我的 ReplyFactoy 是
return [
... ...
'topic_id' => rand(1, 30),
];
而我的 topics seeder
public function run()
{
Topic::factory()->count(10)->create();
}
topics 只生成了 10 个,而 reply 的 topic_id 却是 1~30 的随机数,满足不了约束
$table->foreign('topic_id')->references('id')->on('topics')->onDelete('cascade');
解决方案:把 topic 的生成数量调整到和 replyFactory 相匹配即可。
推荐文章: