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
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.
Post new comment