简体   繁体   中英

Integrity constraint violation creating Product in Magento

i'm trying to Create a Product from magento Frontend, but when execute the php code i receive this error:

SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`magento`.`catalog_product_entity`, CONSTRAINT `FK_CAT_PRD_ENTT_ATTR_SET_ID_EAV_ATTR_SET_ATTR_SET_ID` FOREIGN KEY (`attribute_set_id`) REFERENCES `eav_attribute_set` (`attribute_set_id`) ON DE)

I found here: Create a product from PHP - Magento that should be a problem with attribute set ID, but i tried force the ID from eav_attribute_set table, then with the function:

Mage::getModel('catalog/config')->getAttributeSetId('catalog_product','Set_evento')

And with this function above but with "Default" value. Nothing change. So maybe the problem is not Attribute Set ID?

This is my code:

$product = Mage::getModel('catalog/product');

$product->setSku(time());
$product->setName("Evento senza nome");
$product->setDescription("123");
$product->setShortDescription("1234");
$product->setPrice(0.00);
$product->setTypeId('virtual');
$attributeSetId = Mage::getModel('catalog/config')->getAttributeSetId('catalog_product','Set_evento');
$product->setAttributeSetId($attributeSetId); 
$product->setCategoryIds(array($cat_id)); 
$product->setVisibility(4); // catalog, search
$product->setStatus(1); // enabled

// assign product to the default website
$product->setWebsiteIds(array(Mage::app()->getStore(true)->getWebsite()->getId()));

// for stock
$stockData = $product->getStockData();
$stockData['qty'] = 1;
$stockData['is_in_stock'] = 1;
$product->setStockData($stockData);

$product->setCreatedAt(strtotime('now'));

Mage::app()->getStore()->setId(Mage_Core_Model_App::ADMIN_STORE_ID);

$product->save();

Thanks!

Please check if you have set a valid $attributeSetId , if Mage::getModel('catalog/config')->getAttributeSetId('catalog_product','Set_evento') successfully returned a valid ID.

I had the same error and setting a valid attribute set ID solved the problem for me.

Basically foreign key constraint errors are caused by you trying to enter a value into that column that does not exist in the referenced table. In this case - I'd check to see whether the value you're trying to insert into your primary table is allowed in your secondary table.

I had the same issue while running an importer, i found that the problem was some of the products i was trying to update did not exist adding this code worked for me.

$productid = Mage::getModel('catalog/product')
            ->getIdBySku(trim($sku));
        if(!$productid){
            Mage::Log('Failed to load product with Sku:'.$sku,null,'cron.log');
            return;
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM