如何对Magento中的集合进行排序?
问题描述:
我试图通过attribute_id
对收集进行排序。我认为这将是容易的,但我觉得我没有正确使用它:如何对Magento中的集合进行排序?
$attributes = Mage::getResourceModel('eav/entity_attribute_collection')
->setOrder('attribute_id');
echo $attributes->getSelect();
结果:
SELECT `main_table`.* FROM `eav_attribute` AS `main_table`
为什么没有任何order by
?
答
你实际上正在做它正确的方式。但是,由于Magento使用EAV,它需要应用技巧来提高性能。
这些技巧之一是用于构建最终SQL字符串的时机。通常它在最后一分钟被懒惰地加载,直到你实际上表明你想要访问一个集合的数据,你才能看到用来产生集合的完整SQL。例如运行你的代码,但是促使magento实际构造和加载集合,产生预期的输出。
$attributes = Mage::getResourceModel('eav/entity_attribute_collection')
->setOrder('attribute_id');
$attributes->count(); // forces the collection to load
echo $attributes->getSelect()->assemble();
这将导致SQL:
SELECT `main_table`.* FROM `eav_attribute` AS `main_table` ORDER BY attribute_id DESC
那么你是在正确的道路上,只是Magento的正在做的最好水平来迷惑你。这非常好。
答
使用此而不是$attributes->getSelect();
:
$attributes->getSelect()->order('main_table.attribute_id ASC');
不要问为什么。
不能在Magento 1.4.0.0上工作:无法识别的方法'getSelect()' – frinux 2011-01-26 11:02:27
@frinux你的问题是关于`getSelect()` – powtac 2011-06-16 22:21:00