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

fri*_*nux 13 php sorting collections magento

我正在尝试对一个集合进行排序attribute_id.我觉得这很容易,但我想我没有正确使用它:

$attributes =  Mage::getResourceModel('eav/entity_attribute_collection')
    ->setOrder('attribute_id');
echo $attributes->getSelect();
Run Code Online (Sandbox Code Playgroud)

结果:

SELECT `main_table`.* FROM `eav_attribute` AS `main_table`
Run Code Online (Sandbox Code Playgroud)

为什么没有order by

Aar*_*ner 25

你实际上是以正确的方式做到这一点.但是,由于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();
Run Code Online (Sandbox Code Playgroud)

这导致了SQL:

SELECT `main_table`.* FROM `eav_attribute` AS `main_table` ORDER BY attribute_id DESC
Run Code Online (Sandbox Code Playgroud)

所以你走在了正确的道路上,只是Magento正在尽最大努力让你迷惑.它非常擅长.

  • `setOrder()`导致`desc`顺序.有没有办法让它成为'asc`? (2认同)
  • - > setOrder('attribute_id','asc'); (2认同)