Magento - FK_CAT_CTGR_PRD_IDX_PRD_ID_CAT_PRD_ENTT_ENTT_ID foreign key constrait when trying to re-index Category Products

StackOverflow https://stackoverflow.com/questions/23568130

  •  19-07-2023
  •  | 
  •  

Question

The title says it all really - I'm getting an FK constraint failure when trying to re-index Category Products.

Full exception is:

There was a problem with reindexing process.SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails 
(`krcscouk`.`catalog_category_product_index`, CONSTRAINT `FK_CAT_CTGR_PRD_IDX_PRD_ID_CAT_PRD_ENTT_ENTT_ID` FOREIGN KEY (`product_id`) REFERENCES `catalog_product_entity` (`entity_id`) ON DELETE)

I've seen it happen on flat tables before, but never on Category Products, and I'm not sure which tables I'll need to look at to get it playing nicely.

Was it helpful?

Solution

The error has your answer: FK_CAT_CTGR_PRD_IDX_PRD_ID_CAT_PRD_ENTT_ENTT_ID

FK -> Foreign Key
CAT_CTGR_PRD_IDX -> Table Catalog_Category_Product_Index
PRD_ID -> Column Product_ID from the table above
CAT_PRD_ENTT -> Table Catalog_Product_Entity
ENTT_ID -> Column Entity_ID from the table above

So, your problem is that a foreign key from one of these tables to the other fails. Most likely, you have deleted a product and left something in the Catalog_Category_Product_Index. Run the following selects on your database:

SELECT * FROM catalog_category_product_index WHERE product_id NOT IN (SELECT entity_id FROM catalog_product_entity)

Delete those rows from your database and the index process should work.

OTHER TIPS

  1. Go to PhpMyAdmin and run this query:

    ALTER TABLE catalog_category_product_index DROP FOREIGN KEY FK_CAT_CTGR_PRD_IDX_PRD_ID_CAT_PRD_ENTT_ENTT_ID

  2. Run Reindexing from Magento Admin Panel or from CLI;

  3. After the reindexing is complete, run this query from PhpMyAdmin:

    DELETE FROM catalog_category_product_index WHERE product_id not in (select entity_id from catalog_product_entity); ALTER TABLE catalog_category_product_index ADD CONSTRAINT FK_CAT_CTGR_PRD_IDX_PRD_ID_CAT_PRD_ENTT_ENTT_ID FOREIGN KEY (product_id) REFERENCES catalog_product_entity (entity_id) ON DELETE CASCADE ON UPDATE CASCADE;

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top