Magento – Set Page Size on Collection for In-Stock Items Only

collection;product-collectionstock

how do i load a collection in magento that is limited to 10 products but only includes products that are in stock?

what i tried

1:

$productCollection = Mage::getModel('catalog/product')
            ->getCollection()
            ->setPageSize(10);

 Mage::getSingleton('cataloginventory/stock')
       ->addInStockFilterToCollection($productCollection);
 // problem with this method - if one of the ten items are not in stock my
 // collection only has 9 items

problem with this method – if one of the ten items are not in stock my collection only has 9 items

2:

$collection = Mage::getModel('catalog/product')
 ->getCollection()
 ->addAttributeToSelect('*')
 ->joinField('qty',
             'cataloginventory/stock_item',
             'qty',
             'product_id=entity_id',
             '{{table}}.stock_id=1',
             'left')
 ->addAttributeToFilter('qty', array("gt" => 0));
// problem with this method - configurable parent products don't have stock 
// (only the children do), this causes the parents not to show

problem with this method – configurable parent products don't have stock (only the children do), this causes the parents not to show

Any suggestions?

Solution

Here is a more fleshed out version of the correct answer below:

$collection = Mage::getModel('catalog/product')
     ->getCollection()
     ->addAttributeToSelect('*')
     ->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" => 1))
        ->setPageSize(10);

Best Answer

is_in_stock should probably used to determined if something is in stock, instead of the qty you're using in the join. See below method for Magento's approach.

See Mage_CatalogInventory_Model_Resource_Stock::setInStockFilterToCollection for details.

Related Topic