Sort by association count in Grails

前端 未结 2 1801
感动是毒
感动是毒 2021-01-14 05:07

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

2条回答
  •  旧时难觅i
    2021-01-14 05:34

    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.

提交回复
热议问题