0

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;
    }
1
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;
}
  • After the above small change your method increased the speed of this function by almost a factor of ten (this was only one run, but still, thank you). – easymoden00b Mar 6 '15 at 14:25
  • You're right, I eddited my answer. – SeStro Mar 6 '15 at 21:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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