Downloads

Google Ad

Fetching a random database entry with cakePHP

Date: Wed, Feb 18th 2009, 17:07 Author: nick Views: 8255 Comments share
Using AppModel to write our wrapper findRandom function allows us to retrieve a random record from any model we choose.


  1. class AppModel extends Model {
  2.  
  3.   function findRandom(){
  4.     $this->id = null;
  5.     return $this->find('first', array('order' => 'rand()'));
  6.   }
  7. }

Since we're using AppModel which all models extend from, we can use findRandom in any cake model.

Example:

  1. $random_post = $this->Post->findRandom();
  2. $this->set(compact('random_post'));