Magento – Get products in stock with qty > 0 of configurable products

collection-filteringmagento-1.7product-collectionstock

Whats the best way to get a collection with products which are in stock and have a positive qty.

I already use the following to filter in stock, but this give me also products with qty=0, because I allow backorders

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

Best Answer

How about his - you check that the quantity is greater than 0:

$in_stock_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));

EDIT:

Ok, so I suppose you need to grab the configurable products, and then for each item check if they are in stock? Unfortunately I do not have any stores with configurable items to test this on.

// get your configurable products collection
$_productCollection = Mage::getResourceModel('catalog/product_collection')
                        ->addAttributeToSelect('*')
                        ->addAttributeToFilter('type_id','configurable'); 


// then loop through and check each product if in stock
foreach ($_productCollection as $product) {

    $stock = Mage::getModel('cataloginventory/stock_item')->loadByProduct($product)->getQty();

    echo $product->getName() . ' has a stock of value of ' . $stock;
    echo '<br />';
}