Reputation: 2557
I add Foreign Keys to my app. There I have tables for comments
, games
, films
and books
. When I create comment for games, I set field game_id
to the ID of current game, but appears this error:
SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`chooseone`.`tbl_comments`, CONSTRAINT `FK_books_comments` FOREIGN KEY (`book_id`) REFERENCES `tbl_books` (`id`) ON DELETE CASCADE ON UPDATE CASCADE). The SQL statement executed was: INSERT INTO `tbl_comments` (`content`, `game_id`, `author_id`, `created`, `updated`) VALUES (:yp0, :yp1, :yp2, :yp3, :yp4)
I already find related posts, and try do some changes(e.g.change INT(10)
in table comments
into INT(11)
etc.), but error still here. Can somebody help me?
Upvotes: 0
Views: 243
Reputation: 5187
The error message contains all the information you need for this problem:
SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails
The above indicates that the problem is in the child row (which is generally going to be the case when inserting.)
CONSTRAINT `FK_books_comments` FOREIGN KEY (`book_id`)
REFERENCES `tbl_books` (`id`) ON DELETE CASCADE ON UPDATE CASCADE).
The SQL statement executed was:
INSERT INTO `tbl_comments` (`content`, `game_id`, `author_id`, `created`, `updated`)
VALUES (:yp0, :yp1, :yp2, :yp3, :yp4)
Look at the constraint. You MUST have a book_id
in any rows in the tbl_comments
table, and that book_id
MUST match the id
of a record in the tbl_books
table. You however do not include a book_id
in the insert statement.
Specify the book_id
to resolve this issue.
Upvotes: 1