You need to insert the category_id into the category table first.
Apr 4, 2020
6
Level 30
Cannot add or update a child row: a foreign key constraint fails
This isn't directly Laravel related, but SQL. Maybe someone can help me out. I am getting the above error if i try to insert a new entry to the table.
The category_id and category_version_id which i am trying to insert into my new news table are already existing within the category table. The columns are id and version_id within the category table.
So i don't understand why i am getting the error.
** SQL query **
INSERT INTO `development`.`news` (`id`, `teaser`, `category_id`, `category_version_id`) VALUES ('1', 'dasad', '4550C07D5EBF40BEA01F7A9351D1373C', '0FA91CE3E96A4BC2BE4BD9CE752C3425');
** Error **
Cannot add or update a child row: a foreign key constraint fails (`development`.`news`, CONSTRAINT `fk.news.category_id` FOREIGN KEY (`category_id`, `category_version_id`) REFERENCES `category` (`id`, `version_id`) ON DELETE CASCADE ON UPDATE CASCADE)
** News Table **
CREATE TABLE IF NOT EXISTS `news` (
`id` BINARY(16) NOT NULL,
`teaser` VARCHAR(255) NOT NULL,
`category_id` BINARY(16) NOT NULL,
`category_version_id` BINARY(16) NOT NULL,
`created_at` DATETIME(3) NOT NULL,
`updated_at` DATETIME(3) NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
second migration for the foreign keys
ALTER TABLE `news`
ADD KEY `fk.news.category_id` (`category_id`,`category_version_id`),
ADD CONSTRAINT `news.category_id` FOREIGN KEY (`category_id`,`category_version_id`) REFERENCES `category` (`id`,`version_id`) ON DELETE CASCADE ON UPDATE CASCADE
Please or to participate in this conversation.

