Nirmesh
Nirmesh

Reputation: 305

creating product programatically in magento with table prefix

I am trying to create product in magento programatically. This script works well with default installation. However it shows below error when I try to create a product in those magento installation where I have given table prefix. Can you please tell me what I need to make changes?

Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (databasename_magento.catalog_category_product_index, CONSTRAINT FK_CAT_CTGR_PRD_IDX_CTGR_ID_CAT_CTGR_ENTT_ENTT_ID FOREIGN KEY (category_id) REFERENCES catalog_category_entity (`entity_)

$product = new Mage_Catalog_Model_Product();
$product->setSku($sku);
$product->setAttributeSetId(9);
$product->setTypeId('simple');
$product->setName('55');
$product->setCategoryIds(array(7)); # some cat id's, my is 7
$product->setWebsiteIDs(array(1)); # Website id, my is 1 (default frontend)
$product->setDescription('Gift card Full description here');
$product->setShortDescription('Gift Card Short description here');
$product->setPrice('200'); # Set some price   
$product->setWeight(4.0000);
$product->setVisibility(Mage_Catalog_Model_Product_Visibility::VISIBILITY_NOT_VISIBLE);
$product->setStatus(1);
$product->setTaxClassId(0); # My default tax class
$product->setStockData(array( 'is_in_stock' => 1, 'qty' => 9999 ));

$product->save();

Upvotes: 1

Views: 489

Answers (1)

Ravinder Reddy
Ravinder Reddy

Reputation: 23992

Error message clearly notifying that the foreign key integrity is violated on category_id field.

$product->setCategoryIds(array(7)); # some cat id's, my is 7

Above statement must be causing an error because the value you are setting is not present in the referred parent column catalog_category_entity (entity_id).

Change the input to be an existing value in parent table and run. And it should be working.

Upvotes: 1

Related Questions