Magento 1 – set order of collection
In this tutorial I show you how to set order of collection. It is sometimes quite frustrating to set order, because there are two possible methods. Depending on your collection and column you want to sort, only one works.
Magento 1 – set order of collection
A pre sorted collection is needed if you want to display a list of objects (for example products) in a defined order. Another common task is to quick find a product with a special filter (for example the one with the highest weight in collection). For all this tasks you need to sort collection before you loop it. Basically you have two possibilities:
Sort by eav attributes
Most Magento standard collections use eav models like all product attributes. If you want to sort a collection by one of them, for example sku, you can use method addAttributeToSort() with params attribute name and sort order (ASC or DESC). This may look as follows:
1 | $collection->addAttributeToSort('sku', 'ASC'); |
This method doesn’t work for non eav attributes. If you use a non eav attribute, nothing happens. If you print SQL statement with:
1 | echo $collection->getSelect()->__toString(); |
You will see no “Order By” statement.
Sort by non eav attributes
A completely different method is needed if you want to sort a collection by non eav attributes. This is needed if you create your own tables or if you sort Magento collections that do not use eav attributes (like order or quote collections). You may use order() method of select Statement like this:
1 | $collection->getSelect()->order('product_id', 'DESC'); |
On some sites you also find the following method:
1 | $collection->setOrder('product_id', 'DESC'); |
I’ve read it often, but I think I never used it.
Which method?
If you do not know which method to use, simply try it and print out SQL statement. If “Order By” is missing, then it was the wrong method. Another good solution is to check your database. If your sort attribute is no column and instead defined in eav_attribute, then use eav attribute version.
Conclusion
The question on how to set order of collection is a very common one. Each developer, who needs this may has the problem of not sorted collections. It is hard to find out, because there is no obvious reason why it is not working. If you google it, you may get the wrong version and get frustrated.