Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fix error in MySQL : 1452 - Cannot add or update a child row: a foreign key constraint fails

I run sql query in Navicat, so got error;

Query:

ALTER TABLE `customer_eav_attribute`
  ADD CONSTRAINT `CUSTOMER_EAV_ATTRIBUTE_ATTRIBUTE_ID_EAV_ATTRIBUTE_ATTRIBUTE_ID` 
  FOREIGN KEY (`attribute_id`) 
  REFERENCES `eav_attribute` (`attribute_id`) 
  ON DELETE CASCADE;

Error:

1452 - Cannot add or update a child row: a foreign key constraint
fails (`caterin1_test`.`#sql-dd4_13`, CONSTRAINT
`CUSTOMER_EAV_ATTRIBUTE_ATTRIBUTE_ID_EAV_ATTRIBUTE_ATTRIBUTE_ID`
FOREIGN KEY (`attribute_id`) 
REFERENCES `eav_attribute` (`attribute_id`) 
ON DELETE CA)

How can I fix it?

like image 900
Bohdan V. Avatar asked Oct 24 '25 14:10

Bohdan V.


2 Answers

This is usually happening when you try to source file into existing database. Drop two tables(customer_eav_attribute, eav_attribute). Please create table again.

CREATE TABLE t1
(id INTEGER);

CREATE TABLE t2
(t1_id INTEGER,
 CONSTRAINT FOREIGN KEY (t1_id) REFERENCES t1 (id));

And then set like this.

ALTER TABLE `customer_eav_attribute`
  ADD CONSTRAINT `CUSTOMER_EAV_ATTRIBUTE_ATTRIBUTE_ID_EAV_ATTRIBUTE_ATTRIBUTE_ID` 
  FOREIGN KEY (`attribute_id`) 
  REFERENCES `eav_attribute` (`attribute_id`) 
  ON DELETE CASCADE;
like image 177
Stevan stajo Avatar answered Oct 27 '25 01:10

Stevan stajo


I think there is no linked id in eav_attribute table and customer_eav_attribute table. You must check eav_attribute table and customer_eav_attribute table (best way: plz delete eav_attribute and customer_eav_attribute and then insert data again). You can find solution.

like image 35
Shiba Y. Avatar answered Oct 26 '25 23:10

Shiba Y.