Increasing collection use efficiency (getting product quantities from a collection of skus)

magento.stackexchange https://magento.stackexchange.com//questions/59851

  •  12-12-2019
  •  | 
  •  

Вопрос

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;
    }
Это было полезно?

Решение

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;
}
Лицензировано под: CC-BY-SA с атрибуция
Не связан с magento.stackexchange
scroll top