Ashley Ashley - 1 year ago 77
PHP Question

magento get products from category, order by rand()

I have the following:

$products = Mage::getModel('catalog/product')
->addAttributeToSort('id', 'RAND()')

But I need to order by id
, how can I do this? (The code shows how I've tried with no luck)

Answer Source

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.

/* @var $products Mage_Catalog_Model_Resource_Eav_Mysql4_Product_Collection */
$products = Mage::getModel('catalog/product')
$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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download