Question

When I try to use the following code to get 4 products in stock from certain category

 $_helper = $this->helper('catalog/output');
 $_category = Mage::getModel('catalog/category')->load($this->getCategoryId());
 $_productCollection = Mage::getResourceModel('reports/product_collection')
                       ->addAttributeToSelect('*')
->addAttributeToFilter('is_in_stock', 1)
->addAttributeToFilter('qty', ">1")
                       ->addCategoryFilter($_category)
                       ->setVisibility(array(2,3,4));
 $_productCollection->getSelect()->order(new Zend_Db_Expr('RAND()'));                  
 $_productCollection->setPage(1, 4);

I got the following exception

Fatal error: Call to a member function getBackend() on a non-object in /home/xxx/public_html/app/code/core/Mage/Eav/Model/Entity/Abstract.php on line 816
Was it helpful?

Solution

Try to get the product collection like this:

$_productCollection = Mage::getResourceModel('reports/product_collection')
                       ->addAttributeToSelect('*')
                       ->addCategoryFilter($_category)
                       ->setVisibility(array(2,3,4));
Mage::getSingleton('cataloginventory/stock')->addInStockFilterToCollection($_productCollection); //this should filter in stock products only
$_productCollection->getSelect()->order(new Zend_Db_Expr('RAND()'));                  
$_productCollection->setPage(1, 4);

OTHER TIPS

This error occurs usually due to calling up the wrong model, or applying a filter to an attribute that doesn't exist in that collection double-check that the product attribute id exists on your current magento go to Admin check your attributes and match the keys with

->addAttributeToFilter('is_in_stock', 1)
->addAttributeToFilter('qty', ">1")

Make sure you have the in stock attribute with this is_in_stock identifier ans same for qty

Note please tag your question with the version you are using in your case it is 1.4 or 1.7 ? Also magento officially supports the Linux environment

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top