1

I am using the following code to get five Best sellers collection. The number five is fixed here.

// Array of Id's to retrieve from product collection
$dataArray = array(2, 8 , 17, 3, 7);
$collection = Mage::getResourceModel('reports/product_collection')
        ->addFieldToFilter('entity_id', $dataArray)
        ->addAttributeToSelect('*');
// shuffling the retrieved collection
$collection->getSelect()->order(new Zend_Db_Expr('RAND()'));
// limiting the collection to number 5
$collection->setPageSize(5);

$dataArray is a variable which holds the product ids.

In above code, the $dataArray can have less than five ids. In those cases, I am getting the collection less than five. But my requirement is that the collection must have five products even the $dataArray holds less than 5 values. I mean the remaining product collection should come from the same Bestsellers collection excluding the $dataArray values.

How should I do this?

I can do this something like this, which I think is not good for performance:

 $count = count($collection);
 if($count < 5){
     $remainingCount = 5 - $count;
     // Again run the above product collection
     // exclude the product ids which are already present in array
     // setPageSize to $remainingCount
     // and somehow merge the above specific best sellers with this 
 }
1

Do the same and exclude the IDs:

$remainingCount = 5 - $count;
// Array of Id's to retrieve from product collection
$dataArray = array(2, 8 , 17, 3, 7);
$collection = Mage::getResourceModel('reports/product_collection')
        ->addFieldToFilter('entity_id', $dataArray)
        ->addAttributeToSelect('*');
// shuffling the retrieved collection
$collection->getSelect()->order(new Zend_Db_Expr('RAND()'));
// limiting the collection to number 5
$collection->setPageSize($remainingCount);
// exclude the IDs
$collection->setAttributeToFilter('entity_id', array('nin' => $dataArray));
  • I don't think it is possible to do the attribute filtering to the already attribute filtered collection (two times with entity_id). I am getting error when I tried your code. Fatal error: Call to undefined method Mage_Reports_Model_Resource_Product_Collection::setAttributeToFilter() – Mr_Green May 21 '14 at 4:39
  • Oh no, you need to shot a second collection, sorry. and the method name is addAttributeToFilter, sorry. – Fabian Blechschmidt May 21 '14 at 8:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.