Skip to content

Getting ` 1452 Cannot add or update a child row: a foreign key constraint fails` on Magento 2.4.7-p1

I did a magento update from 2.4.6-p3 -> 2.4.7-p1 and now I cannot create programmatically a product.
Once I am doing:

$product = $this->product->setData($productData);
$this->resourceModelProduct->save($product);

I’m getting this error message:

SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: 
    a foreign key constraint fails (`magento`.`catalog_url_rewrite_product_category`, CONSTRAINT `FK_BB79E64705D7F17FE181F23144528FC8` 
    FOREIGN KEY (`url_rewrite_id`) REFERENCES `url_rewrite` (`url_rewrite_id`) ON DELETE CASCADE), query was: 
    INSERT INTO `catalog_url_rewrite_product_category` (`url_rewrite_id`,`category_id`,`product_id`) VALUES (?, ?, ?), (?, ?, ?), (?, ?, ?), (?, ?, ?), (?, ?, ?), (?, ?, ?), (?, ?, ?), (?, ?, ?), (?, ?, ?), (?, ?, ?), (?, ?, ?), (?, ?, ?) ON DUPLICATE KEY UPDATE `url_rewrite_id` = VALUES(`url_rewrite_id`), `category_id` = VALUES(`category_id`), `product_id` = VALUES(`product_id`)

It is very odd since the table is empty. See:

mysql> select * from catalog_url_rewrite_product_category;
Empty set (0.00 sec)

I also removed all of my category and product urls from the url_rewrite and regenerated it with this plugin: https://github.com/olegkoval/magento2-regenerate_url_rewrites. But I’ve got the same results.
On m2.4.6-p3 , its perfectly working. I also tried this possible fix: https://magento.stackexchange.com/a/322107/6204 , but it does not work for me.

Anyone got this error before and managed to fix it ? Would you please share your thoughts.

Thanks