Retrieving a random record in Symfony using Propel
Just a quicky, as I had to spend 10 mins looking this up hopefully it’ll save someone else time later.
I need to retrieve a random user from the users table, but didn’t know how to express a random record… this method will return a single random user, or can take an argument to return more than 1
UserPeer
public static function getRandomUsers($num=1){ $c = new Criteria(); $c->addAscendingOrderByColumn('rand()'); $c->setLimit($num); $users = UserPeer::doSelect($c); return $users; }
Simple. (and probably documented better somewhere else)
Written by baj | Posted on April 21st, 2008 in symfony |
Newsvine
Email This to a Friend
Subscribe

April 22nd, 2008 at 7:39 am
Your solution is very database specific and probably only works with mysql.
Take a look at the first comment of this snippet: http://www.symfony-project.org/snippets/snippet/25
there’s also a database independent solution there.
Too bad there’s no “clean” way of doing this in Propel 1.2. (Propel 1.3 adds the random() method (http://propel.phpdb.org/trac/ticket/343)).
April 22nd, 2008 at 9:01 am
Yep, I use this on a project of mine. Just be aware it’s not particularly portable, as it relies on MySQL syntax (though it could be similar in, say, Postgres - not sure there).
Btw, it’s nice to see more UK users getting on board symfony :)
April 23rd, 2008 at 2:43 pm
Arthur:
Thanks, yes I was aware of it being limited to using a mysql function call as I was writing it, perhaps not giving enough importance to pointing that out in the post.
Halfer:
Thanks, yeah as Arthur points out, it’s specific to MySQL, perhaps it would work on Postgres, but probably not other DB’s.