Heng-Cheong Leong
Heng-Cheong Leong

Reputation: 864

A model's collection turns out to be a non-object

I am trying to get a list of viewed products in Magento, but the following code:

$model = Mage::getModel('reports/product_index_viewed')->getCollection()
    ->addAttributeToFilter('store_id', array('eq' => 1));

created the error message:

Fatal error: Call to a member function getBackend() on a non-object in C:\xampp\htdocs\magento\app\code\core\Mage\Eav\Model\Entity\Abstract.php on line 816

Why is the collection returned in getCollection() a non-object?

Upvotes: 0

Views: 3137

Answers (1)

Ivan Chepurnyi
Ivan Chepurnyi

Reputation: 9223

You have an error in your filter call. Actually there is no store_id attribute for product and in your case collection tries to get this attribute, but since it doesn't exist an error occurs. In report collection there is a special method created to specify store filter, so you code should look like this (also I included construction for proper type hinting):

/* @var $collection Mage_Reports_Model_Resource_Product_Viewed_Collection */ // This enabled type hinting
$collection = Mage::getModel('reports/product_index_viewed')->getCollection();
$collection->setStoreId($storeId); // Setting data scope (e.g translated names, prices, etc)
$collection->addStoreFilter($storeId); // Set filter by exact availability on this store.

Have fun with Magento development!

Upvotes: 2

Related Questions