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
3、最终决定删除掉 topics 中用户ID等于 9 的记录。再次执行命令,不再报错,外键约束 topics_user_id_foreign 已经添加成功。如图3
原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/tech/webdev/250699.html
![添加外键约束时报错: SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails 。](https://blog.ytso.com/wp-content/themes/justnews/themer/assets/images/lazy.png)