Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

query magento limit + order by rand()

Tags:

magento

function getIdModelsSliderJuwels(){
 $collection = Mage::getModel("catalog/product")->getCollection();
 $collection->addAttributeToFilter("attribute_set_id", 27); 
     $collection->addAttributeToSelect('modellijnen'); 
   //  $collection->setRandomOrder();
   //  $collection->getSelect()->limit( 5 ); 
 return $collection; 
}

Hi there,

I'd like to know how to set a limit to your query running in Magento because $collection->getSelect()->limit( 5 ); doesn't work.

Also how to select randomly, $collection->setRandomOrder(); also doesn't work.

txs.

like image 251
Paul de Zwaan Avatar asked Dec 05 '22 00:12

Paul de Zwaan


2 Answers

setRandomOrder does not work for collections of products, only for related products. You'll have to add it yourself with this code:

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

A shortcut for setting both page size and number at the same time is:

$collection->setPage($pageNum, $pageSize);
like image 142
clockworkgeek Avatar answered Jan 03 '23 03:01

clockworkgeek


As clockworkgeek said, use the $collection->getSelect()->order(...) method to randomize the order. To limit it to just $n number of items you can also use

$collection->getSelect()->limit($n);
like image 29
Janus Tøndering Avatar answered Jan 03 '23 04:01

Janus Tøndering