Question

I have read that one shouldn't use the load() method within a for loop as this is a performance killer, however, i'd like to know how to more efficiency retrieve this information. Below is the current loop that intakes a collection (this collection contains the product sku and the amount of items needed in our inventory for that item to be considered 'in stock') and returns true if all subsequent products are in stock and false if one of the products is out of stock. How could I make it faster, better?

    function inStock($skus){
        if ($skus->getSize()) {
            foreach ($skus as $sku) {
                $product = Mage::getModel('catalog/product');
                $product->load($product->getIdBySku($sku->getSku()));
                $quantity = Mage::getModel('cataloginventory/stock_item')->loadByProduct($product)->getQty();
                if ($quantity < $sku->getRequiredQuantity()) {
                    return false;
                }
            }
        } else {
            return false;
        }
        return true;
    }
Was it helpful?

Solution

function inStock($skus){
    if ($skus->getSize()) {
        $skusArray = array();
        foreach ($skus as $sku) {
            $skusArray[] = $sku->getSku();
            $requiredQtyArray[$sku->getSku()] = $sku->getSku();
        }

        $collection = Mage::getModel('catalog/product')
            ->getCollection()
            ->addAttributeToFilter('sku', array('in' => $skusArray));
        foreach ($collection as $product) {
            $quantity = Mage::getModel('cataloginventory/stock_item')->loadByProduct($product)->getQty();
            if ($quantity < requiredQtyArray[$product->getSku()]) {
                return false;
            }
        }
    } else {
        return false;
    }
    return true;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top