【问题标题】:Count length of hasMany property计算 hasMany 属性的长度
【发布时间】:2014-06-25 18:43:29
【问题描述】:

我有一个域类:

class Person{
 static hasMany = [friends:Person]
 ....
}

我要做的是根据他们拥有的朋友数量过滤掉 Persons。

这就是我想出的,它可以完成这项工作:

Person.where{
 friends.size() == 3
}

它太慢了,我可以不用列表,所以理想情况下我只想运行类似的东西:

select count(*) from Person where size(friends) == 3

我像疯子一样搜索,但在 countBy 上找不到那么多信息(我想我想要做的是 countWhere)。

感谢任何输入。

【问题讨论】:

    标签: hibernate grails hql grails-orm


    【解决方案1】:

    使用where 查询,您应该能够使用count() 而不是列出所有匹配项。 where 创建一个支持多种操作的DetachedCriteria

    Person.where { friends.size() == 3 }.count()
    

    如果这不像我认为的那样有效,您可能需要使用带有投影的条件来仅返回计数。

    Person.withCriteria {
        sizeEq 'friends', 3
        projections {
            rowCount()
        }
    }
    

    【讨论】:

    • 我会试一试,告诉你进展如何。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-09-06
    • 2015-08-21
    • 1970-01-01
    • 2015-02-09
    • 2015-09-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多