Home » Magento2 August 2010

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)

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.

Hope this helps. Thanks.

Magento

Get New Post by Email

Find me on

FacebookTwitterGoogle+LinkedInRSS Feed