Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Random object from database with GORM

I would like to get a random object from database only with GORM, without using database specific code.

Currently I'm using this:

Tag.executeQuery("from Tag order by rand()", [max: Tag.count()])

But I'm not satisfied with that because I'm using mysql's rand() function. Some people recommend to get all IDs, then choose a random one, and then query for the whole object, but I don't want two queries.

Is there a GORM way to do this? If not pure GORM, then maybe Hibernate solution would do the trick.

(I've seen this question here Grails GORM to return random rows from table?, but it does not help :))

like image 415
Vuk Nikolić Avatar asked Sep 09 '12 22:09

Vuk Nikolić


1 Answers

You can first get a random offset, put max:1 and then execute your query with these pagination parameters!
(Note: you will have to do a count() on your table first but it isnt a very costly operation.)

like image 178
Atharva Johri Avatar answered Nov 16 '22 18:11

Atharva Johri