0

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);
  • 1
    One crappy way to do this is just grab a larger number in your first approach, and only loop through the first 10 when you use them. – musicliftsme Apr 13 '16 at 15:04
  • agreed, but sometimes you don't know how many it will go through to find it and you don't want to load the whole collection ;) – pzirkind Apr 13 '16 at 15:05
1

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.

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.