php 如何在 Magento 中对集合进行排序?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4803495/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to sort a collection in Magento?
提问by frinux
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:
我正在尝试按 对集合进行排序attribute_id
。我认为这很容易,但我认为我没有正确使用它:
$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
?
回答by Aaron Bonner
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. 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.
这些技巧之一是用于构建最终 SQL 字符串的时间。通常它是在最后一分钟延迟加载的,直到您实际表示要访问集合的数据,您才能看到用于生成集合的完整 SQL。例如,运行您的代码,但提示 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. It's very good at that.
所以你走在正确的道路上,只是 Magento 尽其所能来迷惑你。它非常擅长这一点。
回答by powtac
Use this instead of $attributes->getSelect();
:
使用它而不是$attributes->getSelect();
:
$attributes->getSelect()->order('main_table.attribute_id ASC');
Don't ask why.
不要问为什么。