I have developed a custom search engine for our Magento store and I am trying to load the product collection in a very specific order (I have ranked the results according to an algorithm I designed).
I can load the product collection correctly, however it is not in the order that I would like it to be in. Here is basically how it is working now:
My database query basically comes back with a PHP array of product IDs. For this example lets say it looks like this:
$entity_ids = array(140452, 38601 );
Now I can transpose the 140452 and the 38601 and the product collection comes back in the same order each time. I would like the product collection to be in the same order as the ID of the entity ids.
The code I am using to create my collection is as follows:
$products = Mage::getModel('catalog/product')
->getCollection()
->addAttributeToSelect('*')
->addAttributeToFilter('entity_id', array('in' => $entity_ids))
->setPageSize($results_per_page)
->setCurPage($current_page)
->load();
Is there a way to set the sort order to be the order of the $entity_ids array?
Collections inherit from the class
There’s a method named
addOrderon that class.So, you’d think something like this should work for basic ordering
However, it doesn’t. Because of the complex joining involved in EAV Collections, there’s a special method used to add an attribute to the order clause
However again, this can only be used to add simple attributes. To create an arbitrary sort, you’ll need to manipulate the
Zend_Selectobject directly. I’m not a big fan of this, and I’m not a big fan of using custom mysql functions to achieve things, but it appears it’s the only way to do thisI tested the following code on a stock install and got the desired results. You should be able to use it to get what you want.