Cannot delete or update a parent row: a foreign key constraint fails - MYSQL

You get this error because the user you would like to delete has associated records within the appointments table. You have 2 options:

  1. Delete the associated records from the appointments table first with a separate delete statement.

  2. Add on delete cascade option to appointments_user_id_foreign foreign key. This option will automatically remove any associated records from the appointments table for the user to be deleted when you delete the user's record.

The modified fk statement looks like as follows:

... ADD CONSTRAINT `appointments_user_id_foreign` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE CASCADE;

The solution proposed by @Nebster technically removes the error message, but also enables having orphan records within the appointments table - appointments related to deleted users. Therefore, removing the foreign key is not a sensible option in my opinion.


SET FOREIGN_KEY_CHECKS=0; – to disable them

SET FOREIGN_KEY_CHECKS=1; – to re-enable them


When you're deleting from phpMyAdmin, just uncheck enable foreign key checks at bottom

enter image description here

Tags:

Mysql