I need to update the qty of all products (around 15.000 items) in a cycle, but it takes a very long time. How can I build a SQL script within the loop to run it in a single execution?. I have this code:
This takes more than 40 minutes:
$products_from_erp;//array with product data from ERP system
foreach($products_from_erp as $data_product){
$stockItem = Mage::getModel('cataloginventory/stock_item')->loadByProduct($data_product['product_id']);
$stockItem->setQty($data_product['qty']);
$stockItem->setIsInStock(($data_product['qty'] > 0) ? 1 : 0);
$stockItem->save();
}
This takes 15 minutes:
$connection = Mage::getSingleton('core/resource')->getConnection('core_write');
foreach($products_from_erp as $data_product){
$bind = array(
'qty' => $data_product['qty'],
'is_in_stock' => ($data_product['qty'] > 0) ? 1 : 0
);
$where = 'product_id = '.$data_product['product_id'];
$connection->update('cataloginventory_stock_item',$bind,$where);
}
I also tried this code (It should be much faster) but it takes 15 minutes approx:
$connection = Mage::getSingleton('core/resource')->getConnection('core_write');
$sql = "";
foreach($products_from_erp as $data_product){
$qty = $data_product['qty'];
$is_in_stock = ($data_product['qty'] > 0) ? 1 : 0;
$product_id = $data_product['product_id'];
$sql .= "UPDATE cataloginventory_stock_item SET qty = '$qty', is_in_stock = '$is_in_stock' WHERE product_id = $product_id; ";
}
$connection->query($sql);