Code snippets for symfony 1.x


Little trick to randomize results

More a PHP trick than symfony's one, but as you can't with propel randomize order of results, just do:

$c = new Criteria()
... fill your criteria there ...
$result = MyTablePeer::doSelect($c);

obvious? sorry, seen someone asking on IRC once :D

by Romain Dorgueil on 2006-05-29, tagged column  criteria  database  order  propel  random 

Comments on this snippet

gravatar icon
#1 Martin on 2006-05-29 at 08:11

You should't do that if your table contains more than a few records. It'll load all your rows into memory.

There were some other solutions suggested on the Propel mailing list, like here:

So try something like that:

/// should be database independent ///
$phoneCount = PhoneNumberPeer::doCount(new Criteria());
$phoneCriteria = new Criteria();
$phone = PhoneNumberPeer::doSelectOne($phoneCriteria);

or that:

$criteria = new criteria();
/// probably only working with mysql ///
gravatar icon
#2 Jakub Kozisek on 2006-05-30 at 03:40

Thanks Romain and Martin for useful info! :)

gravatar icon
#3 Romain Dorgueil on 2006-05-31 at 10:53

Hoho thought order by rand() wasn't working with propel... thanks for the info, this snipeet stuff is awesome collaborative tool!

gravatar icon
#4 joe simms on 2006-06-12 at 10:28

Does anybody know of an easy way to extend this snipeet to paginate a random result set?

gravatar icon
#5 claire on 2007-11-22 at 06:18

IMHO, the setOffset in Martin's snippet should be : <code>$phoneCriteria->setOffset(rand(0,$phoneCount-1));</code>

gravatar icon
#6 excessive demon on 2007-11-30 at 03:47

Very cool snippet indeed ! :) THanks guys... But I have to say a greater "thanks" to martin as his code is a little better ;)

gravatar icon
#7 zero0x on 2008-02-18 at 09:06

mysql has something like

order by rand()

i think..

gravatar icon
#8 ericfreese on 2009-11-16 at 06:53

To select a random record with doctrine:

$count = Doctrine::getTable('PhoneNumber')->count(); $phoneNumber = Doctrine::getTable('PhoneNumber') ->createQuery() ->limit(1) ->offset(rand(0, $count - 1)) ->fetchOne();