Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

magento get products from category, order by 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)

like image 528
Ashley Avatar asked Dec 04 '10 21:12

Ashley


1 Answers

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.

$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
like image 190
Andrey Korolyov Avatar answered Oct 06 '22 01:10

Andrey Korolyov