Magento 2 – How to Get Product Collection of Out of Stock Items?

cataloginventorycollection;out-of-stockproductproduct-collection

I have a requirement to display a category's products in two lists – one for in stock items, the other for out of stock items.

I'm using

Mage::getSingleton('cataloginventory/stock')->addInStockFilterToCollection()

to filter my product collection for the in stock items, but there doesn't appear to be an equivalent method to filter for out of stock items – I've looked at the Mage_CatalogInventory_Model_Stock model, which is where the aforementioned method is defined.

I have seen the following example for retrieving out of stock products:

$collection->joinField(
                    'is_in_stock',
                    'cataloginventory/stock_item',
                    'is_in_stock',
                    'product_id=entity_id',
                    '{{table}}.stock_id=1',
                    'left'
            )
            ->addAttributeToFilter('is_in_stock', array('eq' => 0));

…but surely this isn't only or best way to achieve this?

Best Answer

let's say that $collection is your product collection that you build like this:

$collection = Mage::getModel('catalog/product')->getCollection()
    ->...additional filters here...;

now do this to your collection. This joins the collection with the stock status table.

$website = Mage::app()->getWebsite();
Mage::getModel('cataloginventory/stock_status')->addStockStatusToSelect($collection, $website);

Now you can filter the out of stock products:

$collection->getSelect()->where('stock_status.stock_status = ?', 0);
Related Topic