magento 从类别中获取产品,通过 rand() 排序
我有以下内容:
$products = Mage::getModel('catalog/product')
->getCollection()
->addAttributeToSort('id', 'RAND()')
->addAttributeToSelect('small_image')
->addCategoryFilter(Mage::getModel('catalog/category')->load($catId));
但我需要按 id RAND()
排序,我该怎么做? (代码显示了我如何尝试但没有运气)
I have the following:
$products = Mage::getModel('catalog/product')
->getCollection()
->addAttributeToSort('id', 'RAND()')
->addAttributeToSelect('small_image')
->addCategoryFilter(Mage::getModel('catalog/category')->load($catId));
But I need to order by id RAND()
, how can I do this? (The code shows how I've tried with no luck)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
Magento 集合不接受除所选属性之一之外的参数。在这种情况下,您应该获取
Zend_Db_Select
对象并向其添加订单指令。要查看将执行什么查询,您可以使用此结构
Magento collection do not accept parameters other then one of selected attribute. In this case you should get
Zend_Db_Select
object and add order instruction to it.To see what query will be executed you may use this construnction
参考这个问题:query magento limit + order by rand() 和clockworkgeek的答案:
Refer to this question: query magento limit + order by rand() and clockworkgeek's answer:
使用 ORDER BY RAND() 以随机顺序返回项目列表将需要全表扫描和排序。它会对表中大量行的性能产生负面影响。
对于如何优化此查询,有几种可能的替代解决方案。 Magento 为此提供了本地解决方案。
Varien_Db_Select
的orderRand()
方法和数据库适配器允许为ORDER BY
指定随机订单和杠杆索引。指定要在 ORDER BY 子句中使用的某些整数索引列的名称,例如:
有关实现详细信息,请参阅
Varien_Db_Adapter_Pdo_Mysql::orderRand()
。Using
ORDER BY RAND()
to return a list of items in a random order will require a full table scan and sort. It can negatively affect performance on large number of rows in the table.There are several alternative solutions possible of how to optimize this query. Magento provides a native solution for that.
The
orderRand()
method ofVarien_Db_Select
and the database adapter allows to specify a random order and leverage index forORDER BY
.Specify a name of some integer indexed column to be used in the
ORDER BY
clause, for example:See
Varien_Db_Adapter_Pdo_Mysql::orderRand()
for implementation details.