0

I am using this code to add a stock item:

$stockItem = Mage::getModel('cataloginventory/stock_item');
$stockItem->setData(array(
                   'use_config_manage_stock' => 0,
                   'manage_stock'=>1, 
                   'min_sale_qty'=>1,
                   'max_sale_qty'=>2,
                   'is_in_stock' => 1,
                   'qty' => 999
               )
);
$stockItem->save();

I am getting this error:

Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (usr_web29785976_1.cataloginventory_stock_item, CONSTRAINT FK_CATINV_STOCK_ITEM_PRD_ID_CAT_PRD_ENTT_ENTT_ID FOREIGN KEY (product_id) REFERENCES catalog_product_entity (entity_id) ON)' in /var/www/web29785976/html/magento/lib/Zend/Db/Statement/Pdo.php:228 Stack trace: #0 /var/www/web29785976/html/magento/lib/Zend/Db/Statement/Pdo.php(228): PDOStatement->execute(Array) #1 /var/www/web29785976/html/magento/lib/Varien/Db/Statement/Pdo/Mysql.php(110): Zend_Db_Statement_Pdo->_execute(Array) #2 /var/www/web29785976/html/magento/app/code/core/Zend/Db/Statement.php(291): Varien_Db_Statement_Pdo_Mysql->_execute(Array) #3 /var/www/web29785976/html/magento/lib/Zend/Db/Adapter/Abstract.php(480): Zend_Db_Statement->execute(Array) #4 /var/www/web29785976/html/magento/lib/Zend/Db/Adapter/Pdo/Abstract.php(238): Zend_Db_Adapter_Abstract->query('INSERT in /var/www/web29785976/html/magento/lib/Zend/Db/Statement/Pdo.php on line 235

2 Answers 2

1

Your stock item has no product assigned, which is required.

// assuming you have a $product
$stockItem->assignProduct($product);
$stockItem->save();
6
  • Doesn't work, I'm still getting the same error.
    – asc11
    Commented Oct 3, 2016 at 12:12
  • Is $product an instance of Mage_Catalog_Model_Product? Commented Oct 3, 2016 at 12:23
  • Yep. It's a product generated by duplication.
    – asc11
    Commented Oct 3, 2016 at 14:31
  • Can you check that the product has an id value? Commented Oct 3, 2016 at 17:42
  • Yes, it has. I already tried to put $new->save before $stockItem, but it didn't work too.
    – asc11
    Commented Oct 4, 2016 at 12:08
0

This is caused by the fact that a stock item must be linked to a product id.

If you want to update an existing stock item you can load it using the product id first:

$stockItem = Mage::getModel('cataloginventory/stock_item')->loadByProduct($productId);

If you want to create a stock item for a new product you can assign the product id by doing:

$stockItem->assignProduct($product);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.