Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort a collection in Magento?

I'm trying to sort a collection by attribute_id. I thought it would be easy, but I think I'm not using it correctly:

$attributes =  Mage::getResourceModel('eav/entity_attribute_collection')
    ->setOrder('attribute_id');
echo $attributes->getSelect();

Result:

SELECT `main_table`.* FROM `eav_attribute` AS `main_table`

Why isn't there any order by?

like image 308
frinux Avatar asked Jan 26 '11 10:01

frinux


People also ask

How do I reorder products in Magento?

To change the product sorting, navigate to Catalog > Categories and choose the Store View that you want to change. Then select the needed category, open the Products in Category tab, and edit the Position column. Save the changes.

What are collections in Magento 2?

Collections in Magento are extremely useful, they allow you to retrieve objects such as products, categories, customers, etc. Retrieving these objects in a collection is a simple case of instantiating an instance of the object entity's factory class and using the model's 'getCollection' method, as follows.


1 Answers

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

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

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

This results in the SQL:

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

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

like image 114
Aaron Bonner Avatar answered Sep 18 '22 07:09

Aaron Bonner