Set Random Order Collection using RAND() In Magento



Suppose you have developed an extension in Magento, and stored all the data into the database and you want to display that data on the frontend randomly. In MySql the rand() function helps the select query to fetch data randomly. In Magento, you can select random rows from MySQL table using Zend_Db_Expr('RAND()')

For using the rand() you have to create a new function in your modules collection class (Namespace/YourCustomModule/Model/Mysql4/YourModule/Collection.php)

public function setRandomOrder()
{
$this->getSelect()->order(new Zend_Db_Expr('RAND()'));
return $this;
}

Now, you are ready to fetch random data from your database table using the setRandomOrder() function. You can display the randon products into the .phml file by using the setRandomOrder(). The Syntax is given below:

<?php
$custom_collection = Mage::getModel('yourcustommodule/yourcustommodule')
->getCollection()
->setRandomOrder();
echo "<pre>";
print_r($custom_collection->getData());
echo "</pre>";

?>

if you want to give the limit that you want to display only the 5,10,15 or 1 products at a time the use “->setPageSize(1)” in the above code then code will look like as below:

<?php
$custom_collection = Mage::getModel('yourcustommodule/yourcustommodule')
->getCollection()
->setPageSize(1) //right now I have display only one produts at a time so that I have putted 1 and you can change it as per your requirement.
->setRandomOrder();
echo "<pre>";
print_r($custom_collection->getData());
echo "</pre>";
?>

Hope this helps, Happy Coding In Magento