Question

I’m looking for a faster way to retrieve a list of SKUs of "in stock" products.

I’m using this code

$products_collection = \Mage::getResourceModel('catalog/product_collection')->addAttributeToSelect('sku');

\Mage::getSingleton('cataloginventory/stock')->addInStockFilterToCollection($products_collection);

return $products_collection->getColumnValues('sku');

but it’s quite slow, because first it gets all products then filter them by "in stock".

Are there any faster query to execute? Maybe using an inverse style: first get only IDs of "in stock" products then get only their SKUs?

Was it helpful?

Solution

Try this

$resource = Mage::getResourceSingleton('catalog/product');
$read = $resource->getReadConnection();
$select = $read->select()
    ->from(array('p' => $resource->getTable('catalog/product')), 'sku')
    ->joinInner(
        array('i' => $resource->getTable('cataloginventory/stock_item')),
        'i.product_id = p.entity_id AND i.is_in_stock=1',
        array()
    );

$skus = $read->fetchCol($select);

OTHER TIPS

You can try join() and where()

$collection = Mage::getModel('catalog/product')->getCollection();
$collection->getSelect()->join('cataloginventory_stock_status', 'cataloginventory_stock_status.product_id = e.entity_id', array('stock_status'));
$collection->getSelect()->where("`cataloginventory_stock_status`.`stock_status` = 1");

$collection is loaded with only In Stock items. Hope this helps.

Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top