Magento – product collection still show not in stock products

collection-filteringmagento-1.9product-collectionproduct-listrelated-products

Hi I'm going crazy with this function. Although I added In stock Filter, it still return Not in Stock products. Where I'm wrong ?

public function getRelatedProducts($limit = false) {
        $product = Mage::registry('current_product');

        if ($category = Mage::registry('current_category')) {

        } elseif ($product) {
            $ids = $product->getCategoryIds();

            if (!empty($ids)) {
                $category = Mage::getModel('catalog/category')->load($ids[0]);
            }
        }

        if ($category) {
            if ($limit === false) {
                $limit = Mage::getStoreConfig('autorelated/general/limit');
            }

            $products = Mage::getResourceModel('catalog/product_collection')
                ->addAttributeToFilter('visibility', array(
                    Mage_Catalog_Model_Product_Visibility::VISIBILITY_BOTH,
                    Mage_Catalog_Model_Product_Visibility::VISIBILITY_IN_CATALOG
                ))
                ->addAttributeToFilter('status', 1)
                ->addAttributeToFilter('is_in_stock', 1)
                ->addAttributeToFilter('qty', array("gt" => 0))
                ->addAttributeToFilter ('price', array ('gt' => 1))
                ->addCategoryFilter($category)
                ->addAttributeToSelect('*')
                ->setPageSize($limit);

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


            if ($product) {
                $products->addAttributeToFilter('entity_id', array(
                    'neq' => Mage::registry('current_product')->getId())
                );
            }

            $products->getSelect()->order('updated_at','desc');



        } else {
            return false;
        }

    return $products;
}

Best Answer

Try this:

Way 1:

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

Way 2:

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