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)
Refer to this question: query magento limit + order by rand() and clockworkgeek's answer:
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 theORDER BY
clause, for example:See
Varien_Db_Adapter_Pdo_Mysql::orderRand()
for implementation details.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