没有不值得去解决的问题,也没有不值得去学习的技术!

添加外键约束时报错: SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails

添加外键约束时报错: SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails 。
1、添加外键约束时报错: SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails 。如图1
添加外键约束时报错: SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails 。
图1


PS E:\wwwroot\larabbs> php artisan migrate
Migrating: 2022_01_05_170327_add_references

   Illuminate\Database\QueryException

  SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`larabbs`.`#sql-13d0_5a1`, CONSTRAINT `topics_user_id_foreign` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE CASCADE) (SQL: alter table `topics` add constraint `topics_user_id_foreign` foreign key (`user_id`) references `users` (`id`) on delete cascade)

  at E:\wwwroot\larabbs\vendor\laravel\framework\src\Illuminate\Database\Connection.php:703
    699▕         // If an exception occurs when attempting to run a query, we'll format the error
    700▕         // message to include the bindings with SQL, which will make this exception a
    701▕         // lot more helpful to the developer instead of just the database's errors.
    702▕         catch (Exception $e) {
  ➜ 703▕             throw new QueryException(
    704▕                 $query, $this->prepareBindings($bindings), $e
    705▕             );
    706▕         }
    707▕     }

  1   E:\wwwroot\larabbs\vendor\laravel\framework\src\Illuminate\Database\Connection.php:492
      PDOException::("SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`larabbs`.`#sql-13d0_5a1`, CONSTRAINT `topics_user_id_foreign` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE CASCADE)")

  2   E:\wwwroot\larabbs\vendor\laravel\framework\src\Illuminate\Database\Connection.php:492
      PDOStatement::execute()
PS E:\wwwroot\larabbs>


2、分析原因,用户ID等于 9 的记录在 topics 中存在,但是在 users 中已经不存在所导致。如图2
分析原因,用户ID等于 9 的记录在 topics 中存在,但是在 users 中已经不存在所导致。
图2
3、最终决定删除掉 topics 中用户ID等于 9 的记录。再次执行命令,不再报错,外键约束 topics_user_id_foreign 已经添加成功。如图3
最终决定删除掉 topics 中用户ID等于 9 的记录。再次执行命令,不再报错,外键约束 topics_user_id_foreign 已经添加成功。
图3

PHP / Laravel / Yii2 老项目维护与长期技术支持

如果你的 PHP / Laravel / Yii2 项目已经上线,但遇到原开发离职、Bug 长期无人修复、接口不稳定、性能下降、代码难以接手等问题,可以联系我做一次远程技术排查。

适合以下情况:
✅ 老旧 PHP 系统无人维护
✅ Laravel / Yii2 项目 Bug 修复
✅ 后台管理系统小功能迭代
✅ RESTful API 接口排查
✅ MySQL / Redis / Nginx 性能问题
✅ 长期远程兼职维护

可先从一次小问题开始:
✅ 线上报错排查
✅ 接口异常分析
✅ 慢查询与性能瓶颈定位
✅ 代码结构初步评估
✅ 部署环境与日志检查

如需咨询,请联系我,并注明:PHP 维护咨询

联系方式:
Telegram:@shuijingwan
微信:13980074657
邮箱:shuijingwanwq@gmail.com

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理