1. An error occurred when adding the foreign key constraint: SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails. See Figure 1.
![An error occurred when adding the foreign key constraint: SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails.](https://media.shuijingwanwq.com/2022/01/1-11.png)
Plaintext
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. After analyzing the cause, the issue occurs because a record with user ID 9 exists in the topics table, but no longer exists in the users table. See Figure 2.

3. I finally decided to delete the record with user ID 9 from the topics table. Running the command again no longer produced an error, and the foreign key constraint topics_user_id_foreign was successfully added. See Figure 3.

