Magento: Set Random Order in Collection using RAND()
Scenario:
You have created a custom module.
You have entered certain data in your database.
You need to show the data randomly.
Solution:
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()’).
You have to create a new function in your module’s collection class (YourNamespace/YourModule/Model/Mysql4/YourModule/Collection.php)
public function setRandomOrder()
{
$this->getSelect()->order(new Zend_Db_Expr('RAND()'));
return $this;
}
Now, you can fetch random data from your table using the above create setRandomOrder function. The code below can be kept in the block or template (.phtml) file of your module.
$collection = Mage::getModel('yourmodule/yourmodule')
->getCollection()
->setRandomOrder();
echo "<pre>"; print_r($collection->getData()); echo "</pre>";
Hope this helps. Thanks.
Related posts:
- Generating random image
- Random number, string generation in PHP
- Magento: Very Useful Collection Functions
- PHP: Generating Multiple Random String
- Magento: How to filter product collection using 2 or more category filters?
- Magento: Get country and region collection
- Magento: Get Product Collection by Type
- jQuery: Grey out background and preview image as popup
- Magento: Quick way to create order invoice programmatically
- Magento: Displaying / Adding Gift Message in Order
