按照Grails中的关联计数进行排序 [英] Sort by association count in Grails

查看:120
本文介绍了按照Grails中的关联计数进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有许多Topic对象,每个Topic都有许多帖子:Post
如何根据他们的帖子计算所有Topic对象的数量?

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

推荐答案

你可以这样做,但它需要两个查询。这是因为要按集合的大小排序,您需要使用分组依据,但这需要您枚举所有主题属性。如果您添加或删除一个查询将会中断。所以解决方法是运行一个查询找到有序的id,第二个获取这些id的实例:

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)

这篇关于按照Grails中的关联计数进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆