[ACCEPTED]-How to sort a collection in Magento?-magento

Accepted answer
Score: 25

You're actually doing it the right way. However, since 14 Magento uses EAV, it needs to apply tricks 13 to help performance.

One of these tricks 12 is the timing used to build the eventual 11 SQL string. Usually it's lazily loaded at 10 the last minute and it's not until you actually 9 indicate you want to access a collection's 8 data, that you can see the full SQL used 7 to produce the collection. For example running 6 your code, but prompting magento to actually 5 construct and load the collection, produces 4 the expected output.

$attributes =  Mage::getResourceModel('eav/entity_attribute_collection')
$attributes->count(); // forces the collection to load
echo $attributes->getSelect()->assemble();

This results in the 3 SQL:

SELECT `main_table`.* FROM `eav_attribute` AS `main_table` ORDER BY attribute_id DESC

So you were on the right path, just 2 Magento was doing its level best to confuse 1 you. It's very good at that.

Score: 4

Use this instead of $attributes->getSelect();:

$attributes->getSelect()->order('main_table.attribute_id ASC');

Don't ask why.


More Related questions