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... :) ...

3 comments:

  1. Great Post,

    Your post is really helpful and more simple to understand.

    Thank you so much, Keep posting.

    ReplyDelete
  2. I do agree with all the ideas you have presented in your post. They’re really convincing and will certainly work. Still, the posts are very short for newbies. Could you please extend them a little from next time?..Keep this great work
    magento development company in bangalore 

    ReplyDelete
  3. I know your expertise on this. I must say we should have an online discussion on this. Writing only comments will close the discussion straight away! And will restrict the benefits from this information.
    Newizze

    ReplyDelete