假数据生成不满足约束:无法 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 相匹配即可。

《L01 基础入门》
我们将带你从零开发一个项目并部署到线上,本课程教授 Web 开发中专业、实用的技能,如 Git 工作流、Laravel Mix 前端工作流等。
《G01 Go 实战入门》
从零开始带你一步步开发一个 Go 博客项目,让你在最短的时间内学会使用 Go 进行编码。项目结构很大程度上参考了 Laravel。
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!