简体   繁体   English

如何在Magento中对集合进行排序?

[英]How to sort a collection in Magento?

I'm trying to sort a collection by attribute_id . 我正在尝试按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 ? 为什么没有任何order by

You're actually doing it the right way. 您实际上是在以正确的方式进行操作。 However, since Magento uses EAV, it needs to apply tricks to help performance. 但是,由于Magento使用EAV,因此需要应用技巧来提高性能。

One of these tricks is the timing used to build the eventual SQL string. 这些技巧之一是用于构建最终SQL字符串的时间。 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. 通常,它是在最后一刻被延迟加载的,直到您真正指示要访问集合的数据时,您才可以看到用于生成集合的完整SQL。 For example running your code, but prompting magento to actually construct and load the collection, produces the expected output. 例如,运行您的代码,但提示magento实际构造和加载集合,将产生预期的输出。

$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: 结果是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. 因此,您在正确的道路上,只是Magento尽其所能使您感到困惑。 It's very good at that. 很好。

Use this instead of $attributes->getSelect(); 用它代替$attributes->getSelect(); :

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

Don't ask why. 不要问为什么。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM