View a Random Record in CakePHP

This is a simple action to display a random record. Possibly useful for sites wanting to keep people clicking on something.

The Controller

We find a random record, and then we reuse the current view action and template.

controllers/posts_controller.php
<?php
class PostsController extends AppController {
	var $name = 'Posts';

	function random() {
		// $this->Post->contain(); // use this if you are using Containable
		$random = $this->Post->find('first',array(
			'conditions' => array(
				'Post.active'=>1,
			),
			'order' => 'rand()',
		));
		$this->view($random['Post']['id']);
		$this->render('view');
	}
}
?>

Comments

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.

Had to retrieve something at random and 'order' => 'rand()' worked well.

Thanks.

This would work but it's not very scalable. If the Post table got really large you'd run into performance issues. You'll be sorting the entire table in Mysql before getting the one record.

make a table that holds the id number of the most recent week of post. so you basically have a one field table with primary key index doing that random. you can inner join the results to the actual post. +++FAST

You'll be sorting the entire table in Mysql before getting the one record.

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.

Post new comment

The content of this field is kept private and will not be shown publicly.
  • Allowed HTML tags: <a> <b> <i> <strong> <cite> <em> <code> <pre> <ul> <ol> <li> <dl> <dt> <dd>
  • Lines and paragraphs break automatically.
  • You can enable syntax highlighting of source code with the following tags: <code>, <css>, <diff>, <drupal5>, <html>, <javascript>, <php>. The supported tag styles are: <foo>, [foo]. PHP source code can also be enclosed in <?php ... ?> or <% ... %>.

More information about formatting options

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.