php magento 从类别中获取产品,按 rand() 排序

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4356019/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 12:47:08  来源:igfitidea点击:

magento get products from category, order by rand()

phpcollectionsmagentorandom

提问by Ashley

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)

但我需要按 id 订购RAND(),我该怎么做?(代码显示了我如何尝试但没有运气)

回答by Andrey Korolyov

Magento collection do not accept parameters other then one of selected attribute. In this case you should get Zend_Db_Selectobject and add order instruction to it.

Magento 集合不接受所选属性之一以外的参数。在这种情况下,您应该获取Zend_Db_Select对象并向其添加订单指令。

$products = Mage::getModel('catalog/product')
    ->getCollection()
    ->addAttributeToSort()
    ->addAttributeToSelect('small_image')
    ->addCategoryFilter(Mage::getModel('catalog/category')->load());
$products->getSelect()->order(new Zend_Db_Expr('RAND()'));

To see what query will be executed you may use this construnction

要查看将执行什么查询,您可以使用此构造

$products->load(true, true); // first parameter show sql query in output, second show sql query in var/log/syslog

回答by Jonathan Day

Refer to this question: query magento limit + order by rand()and clockworkgeek's answer:

参考这个问题:query magento limit + order by rand()和clockworkgeek的回答:

$collection->getSelect()->order(new Zend_Db_Expr('RAND()'));

回答by zlik

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.

使用ORDER BY RAND()以随机顺序返回项目列表将需要全表扫描和排序。它会对表中大量行的性能产生负面影响。

There are several alternative solutions possible of how to optimize this query. Magento provides a native solution for that.

有几种可能的替代解决方案来优化此查询。Magento 为此提供了原生解决方案。

The orderRand()method of Varien_Db_Selectand the database adapter allows to specify a random order and leverage index for ORDER BY. Specify a name of some integer indexed column to be used in the ORDER BYclause, for example:

和数据库适配器的orderRand()方法Varien_Db_Select允许为 指定随机顺序和杠杆索引ORDER BY。指定要在ORDER BY子句中使用的某个整数索引列的名称,例如:

$collection->getSelect()->orderRand('main_table.entity_id');

See Varien_Db_Adapter_Pdo_Mysql::orderRand()for implementation details.

Varien_Db_Adapter_Pdo_Mysql::orderRand()实现细节。