Friday 17 April 2015

Magento Collection Ordering / Sorting



Today’s post is about collection sorting. It can be confusing because we have 5 options to choose from the available sorting methods:
 
addOrder(),
setOrder(),
unshiftOrder(),
addAttributeToSort() and
getSelect()->order()

Only setOrder($field, $dir) is available regardless of collection type and system settings.
I will suggest used setOrder().

If you came across any requirement that ask to change an order, but an order is already set on the collection then use unshiftOrder($field, $dir) for flat table collections.

For EAV collections you can use
$collection->getSelect()->reset(Zend_Db_Select::ORDER);  // it will reset the order by clause of collection
And then use  
$collection->setOrder($field, $dir); // set new order by field

Let me know in comments if this has helped you....
Happy Coding... :) ...