Sort by association count in Grails

隐身守侯 提交于 2019-12-01 05:43:53

问题


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


回答1:


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)



回答2:


You can do it in one HQL query with size() function. This way you get Topic instances in one query:

SELECT topic
FROM Topic topic
ORDER BY size(topic.posts)

I've found this on http://docs.jboss.org/hibernate/core/3.3/reference/en/html/queryhql.html, section 14.16 Tips & Tricks.



来源:https://stackoverflow.com/questions/2583210/sort-by-association-count-in-grails

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!