i have a collection of records that i need to update stock. I heard that using "load" on magento makes it slower, and since i use it before updating my stock i wonder if there is a faster way, since i have thousand of products.
Here is code example:
$productCollection = Mage::getResourceModel('catalog/product_collection')
->addFieldToFilter(array(
array('attribute'=>'reference','neq'=>''),
));
//Update Prices and Stock
foreach ($productCollection as $product) {
try {
$reference = $product->getReference();
$res = $products_api->xpath("item/sku[.='{$reference}']/parent::*");
if (count($res) <= 0){
unset($product);
unset($res);
unset($reference);
continue;
}
$product->load($product->getId());
//Search for Stock
$stock = $res[0]->stocks->quantity;
//Update Stock
$product->setStockData(array(
'use_config_manage_stock' => 0,
'manage_stock' => 1,
'is_in_stock' => $stock > 0 ? 1 : 0,
'qty' => $stock,
));
$product->save();
You may try to use the stock item loading instead of the product loading. Please, try to use the code below:
$productCollection = Mage::getResourceModel('catalog/product_collection')
->addFieldToFilter(array(
array('attribute'=>'reference','neq'=>''),
));
//Update Prices and Stock
foreach ($productCollection as $product) {
try {
$reference = $product->getReference();
$res = $products_api->xpath("item/sku[.='{$reference}']/parent::*");
if (count($res) <= 0){
unset($product);
unset($res);
unset($reference);
continue;
}
//Search for Stock
$stock = $res[0]->stocks->quantity;
//Update Stock
$stockItem = Mage::getModel('cataloginventory/stock_item')->loadByProduct($product);
if ($stockItem->getId()) {
$isInStock = $stock > 0 ? 1 : 0;
$stockItem->setQty($stock);
$stockItem->setIsInStock($isInStock);
$stockItem->setManageStock(1);
$stockItem->setUseConfigManageStock(0);
$stockItem->save();
}
Taken from Sonassi blog - Mass update stock levels in Magento - FAST