Posted by: infirock | November 16, 2011

Magento: Set Random Order in Own Collection using RAND() function.

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.


Responses

  1. Good morning,
    Thank you for this post, I had been struggling with this for about an hour!


Leave a comment

Categories