As in other answers suggested one can use the class Mage_CatalogInventory_Model_Stock_Item
directly. But one has to reference the product correctly via a call to setProduct
to have working code both for new and existing stock items.
$stockItem = Mage::getModel('cataloginventory/stock_item')->loadByProduct($product->getId());
$stockItem->setProduct($product)
->setData('stock_id', Mage_CatalogInventory_Model_Stock::DEFAULT_STOCK_ID)
->setData('qty', 1)
->setData('is_in_stock', 1)
->setData('manage_stock', 1)
->setData('use_config_manage_stock', 0)
->setData('use_config_backorders', 0)
->setData('backorders', 0)
->setData('use_config_max_sale_qty', 0)
->setData('max_sale_qty', 1)
->save();
Alternative solution
However if you call $product->save
anyway i would just set the stock data via $product->setStockdata($array)
as follows. This way Magento creates a correct stock item from stock data. Big advantage is that the stock item update happens in the same transaction as $product->save()
. This is important for data consistency.
$stockData = array();
$stockData['qty'] = 1;
$stockData['is_in_stock'] = 1;
$stockData['manage_stock'] = 1;
$stockData['use_config_manage_stock'] = 0;
$stockData['use_config_backorders'] = 0;
$stockData['backorders'] = 0;
$stockData['use_config_max_sale_qty'] = 0;
$stockData['max_sale_qty'] = 1;
$product->setStockData($stockData);
//...
$product->save()