Home » Magento

Magento: Set Random Order in Collection using RAND()

2 August 2010 2,232 views Popularity: 5% Share/Bookmark

email

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:

  1. Generating random image
  2. Random number, string generation in PHP
  3. Magento: Very Useful Collection Functions
  4. PHP: Generating Multiple Random String
  5. Magento: How to filter product collection using 2 or more category filters?
  6. Magento: Get country and region collection
  7. Magento: Get Product Collection by Type
  8. jQuery: Grey out background and preview image as popup
  9. Magento: Quick way to create order invoice programmatically
  10. Magento: Displaying / Adding Gift Message in Order
  • http://topsy.com/blog.chapagain.com.np/magento-set-random-order-in-collection-using-rand/?utm_source=pingback&utm_campaign=L2 Tweets that mention Magento: Set Random Order in Collection using RAND() | Mukesh Chapagain’s Blog — Topsy.com

    [...] This post was mentioned on Twitter by Mukesh Chapagain, Tech Blog. Tech Blog said: Magento: Set Random Order in Collection using RAND() (http://bit.ly/bDiNZB) #collection #Magento #order #query #rand [...]

  • http://ricardomartins.info/ Ricardo Martins

    Excelent post. It was exactly what I was looking for…
    I got almos doing the same…

    $destaque1 = Mage::getModel(‘catalog/product’)
            ->getCollection()
            ->addFieldToFilter(‘special_price’,array(‘notnull’=>’special_price’));

    $destaque1->getSelect()->order(new Zend_Db_Expr(‘RAND()’));