tags:

views:

164

answers:

2

I have a User class that hasMany = [friends:User]

Now I am trying to display the friends list - ${user.friends}

However, I'd like to be able to apply parameters like I can with, for example, User.findAllBy(user, [max:10, sort: 'dateCreated', order: 'desc"])

Can someone kindly tell me how to do this on a one-to-many in Grails / Groovy ?

+1  A: 

I'd use HQL:

String hql = '''
select u from User u, User u2
where u in elements(u2.friends) and u2=:user
order by u.dateCreated desc
'''
int max = ...
int offset = ...
def friends = User.executeQuery(hql, [user: user], [max: max, offset: offset])

You could try to filter the friends collection, but as soon as you do anything with it it'll get fully loaded from the database, so if you only want 10 instances you'll have wasted loading all of the rest.

Burt Beckwith
Thanks! That worked -- Is there a way I can include the total count without having to execute another query? -- for pagination
UltraVi01
No, you need to do two queries since the result query is limited by max and offset but the count can't be, it needs to be the total. Grails simulates this with one type of criteria query that returns a PagedResultList, but under the hood it just runs both queries for you.
Burt Beckwith
A: 

I just came across the GORM Labs plugin for Grails and it offers the following functionality

"For every "hasMany" property, there is now an associated method that takes pagination properties ("offset" and "max") and produces the appropriate page. There is also a "countBars" instance property that will provide the total size of the "bars" collection. This is all done with a separate database query if the collection has not been initialized previously, so you can avoid loading all the elements of the collection"

http://www.grails.org/plugin/gorm-labs

UltraVi01