Thursday, July 20, 2017

[SQL][Resolved] Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails

Error Message:
SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`mhtest`.`test`, CONSTRAINT `tests_type_foreign` FOREIGN KEY (`type`) REFERENCES `options` (`option_id`) ON DELETE CASCADE) (SQL: update `tests` set `slug` = 5555555, `lang` = en, `title` = 5555555,  `type` = 218, `detail` = 44444444, `remarks` = , `updated_at` = 2017-07-21 01:46:02 where test_id` = 2)


There are reasons cause this error, and i double checked the constraint has been set at correct table and referenced to an existing column

In my case there are 2 tables, one is named "tests" and another is "options", a column "type" in table tests was set as foreign key referencing to column "option_id" in "options" table. Foreign key constraint "tests_type_foreign" is used for this relation.

Since error caused by constraint "tests_type_foreign", I found the value i update on column "tests.type" is not exists in table "options.option_id", that means the column you updated with foreign key will be referencing for nothing. So an error caused and won't allow you update.

To solve the problem please double check you are updating /inserting a existing value which's the foreign key referencing to.

Reference:

https://stackoverflow.com/questions/14063652/integrity-constraint-violation-1452-cannot-add-or-update-a-child-row

No comments :

Post a Comment