Magento – Join Stock Information Problems with Flat Products

catalogflatproduct

I have this solution to filter out of stock products by joining a field from cataloginventory/stock_item (the is_in_stock field) from my product collection and this works as intended with non-flat-products. But with flat products enabled it breaks, it shows products which have inventory but have the status of "out of stock". Presumably because the fields aren't available when using flat products, but I'm not sure which other fields I should use then. Here is my code:

if (!Mage::getStoreConfig('cataloginventory/options/show_out_of_stock')) {
        $collection->joinField('is_in_stock', 'cataloginventory/stock_item', 'is_in_stock', 'product_id=entity_id', '{{table}}.stock_id=1', 'left');
        $collection->addAttributeToFilter('is_in_stock', array('eq' => 1));
    }

I tried looking at core code and saw that they use cataloginventory/stock_status for their join, and then filter on the field stock_status. I tried to do this, but this doesn't work. How can I filter out of stock products when using flat products?

Best Answer

When filtering by stock status on a product collection you can use the standard way in magento as follows.

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

This will eventually call setInStockFilterToCollection on Mage_CatalogInventory_Model_Resource_Stock

public function setInStockFilterToCollection($collection)
{
    $manageStock = Mage::getStoreConfig(Mage_CatalogInventory_Model_Stock_Item::XML_PATH_MANAGE_STOCK);
    $cond = array(
        '{{table}}.use_config_manage_stock = 0 AND {{table}}.manage_stock=1 AND {{table}}.is_in_stock=1',
        '{{table}}.use_config_manage_stock = 0 AND {{table}}.manage_stock=0',
    );

    if ($manageStock) {
        $cond[] = '{{table}}.use_config_manage_stock = 1 AND {{table}}.is_in_stock=1';
    } else {
        $cond[] = '{{table}}.use_config_manage_stock = 1';
    }

    $collection->joinField(
        'inventory_in_stock',
        'cataloginventory/stock_item',
        'is_in_stock',
        'product_id=entity_id',
        '(' . join(') OR (', $cond) . ')'
    );
    return $this;
}
Related Topic