2014-02-18 58 views
1

我試圖以編程方式在magento中創建產品。該腳本適用於默認安裝。但是,當我嘗試在那些已給予表前綴的magento安裝中創建產品時,它顯示下面的錯誤。你能告訴我需要做什麼改變嗎?以表格前綴編碼方式在magento中創建產品

完整性約束違規:1452不能添加或更新子行:外鍵約束失敗(databasename_magentocatalog_category_product_index,約束FK_CAT_CTGR_PRD_IDX_CTGR_ID_CAT_CTGR_ENTT_ENTT_ID外鍵(category_id)參考文獻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(); 
+0

你有另一個問題$ product-> setWebsiteIds(array(1)); –

回答

1

錯誤消息清楚地通知category_id字段上的外鍵完整性被觸犯

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

上述聲明必須導致錯誤,因爲您所設置的值不存在於引用的父列catalog_category_entity (entity_id)中。

將輸入更改爲父表中的現有值並運行。它應該工作。

+0

我已經對代碼進行了更改 – Nirmesh

+0

我現在已經評論了setattributeset代碼和setcategory。現在它顯示此錯誤保存此配置時發生錯誤:SQLSTATE [23000]:完整性約束違規:1452無法添加或更新子行:外鍵約束失敗('magento_prefix'.'nirmesh_catalog_product_entity',CONSTRAINT'FK_0B09B337C6C1DFD50D7584CD91175F23' FOREIGN KEY('attribute_set_id')REFERENCES'nirmesh_eav_attribute_set'('attribute_set_id')) – Nirmesh

+0

我已經修復了它自己問題很明顯感謝您向我展示正確的路徑。 實際上,我將屬性設置ID設置爲7,這是用於虛擬數據的magento安裝中的「默認」,但對於簡單的magento安裝,它來自「4」。這是第二個錯誤的原因。我也必須設置真正存在的類別ID。 – Nirmesh

相關問題