I am getting following error while assigning foreign key to existing table column:
ERROR 1452 (23000): Cannot add or update a child row: a foreign key constraint fails (
c_x_parsing
.#sql-787_1
, CONSTRAINT#sql-787_1_ibfk_1
FOREIGN KEY (nct_id
) REFERENCEScdb
(nct_id
))
Below is the my query:
ALTER TABLE c_int ADD FOREIGN KEY (n_id) REFERENCES cdb (n_id);
While my parent table is cdb cdb and child table is c_int.
Please suggest me the solution as I already tried with following commands:
ALTER TABLE cdb ENGINE=InnoDB;
ALTER TABLE c_int ENGINE=InnoDB;
Disable the FOREIGN_KEY_CHECKS variable in MySQL server. — set for the current session: SET FOREIGN_KEY_CHECKS=0; — set globally: SET GLOBAL FOREIGN_KEY_CHECKS=0; Now we can INSERT or UPDATE rows in our table without triggering a foreign key constraint fails.
The error message itself showing there is a foreign key constraint error, which means you are deleting a parent table where the child table contains the Primary table identifier as a foreign key. To avoid this error, you need to delete child table records first and after that the parent table record.
You are getting this constraint check because Ordre table does not have reference OrdreID provided in insert command. To insert value in Ordrelinje, you first have to enter value in Ordre table and use same OrdreID in Orderlinje table. Or you can remove not null constraint and insert a NULL value in it. Hope it helps!!
If you are getting error Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails while using php artisan migrate command after creating a migration file. You can set foreign id column value as nullable with null on delete on delete parent table record.
The issue is not the command, but the data. There's a value in the child table that does not exist in the parent table.
Try using something like this to figure out which data is causing the issue:
SELECT n_id FROM c_int WHERE n_id NOT IN (SELECT n_id FROM cdb)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With