tags:

views:

74

answers:

1

I have many Topic objects and each Topic hasMany posts:Post How can I order all Topic objects based on their posts count??

A: 

You can do it, but it requires two queries. This is because to order by the size of a collection, you need to use a 'group by' but this requires that you enumerate all of your Topic properties. If you add or remove one the query will break. So the solution is to run one query that finds ordered ids, and a second that gets the instances for those ids:

String hql = '''
SELECT t.id
FROM Topic t LEFT JOIN t.posts AS post
GROUP BY t.id
ORDER BY COUNT(post) DESC
'''
def ids = Topic.executeQuery(hql)
def orderedTopics = Topic.getAll(ids)
Burt Beckwith