在 Grails 中按关联计数排序 [英] Sort by association count in Grails

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

问题描述

我有很多主题对象,每个主题都有很多帖子:发布如何根据帖子数对所有主题对象进行排序?

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天全站免登陆