如何计算gorm - grails中1对多关系中的出现次数

时间:2010-04-24 19:43:58

标签: grails dns gorm

我有2个域类

class A {
  ....
  static hasMany = [bs:B]
}
class B {
  int code
  ....
}

如何列出所有A表中B中所有代码的发生次数?

这样的东西
b.each { thisb ->
  int ocurrences = A.bs.findAll{it == thisb}.size()
  ...
}

由于

1 个答案:

答案 0 :(得分:2)

我认为我对这个问题有点困惑的原因是,从技术上讲,它实际上是一个多对多关系,而不是真正的一对多关系。 Grails将为此关系创建一个连接表(“a_b”)(因为B与A没有belongsTo关系)。

你构建a A域的方式hasMany关系是一个集合,所以B只会在“bs”集合中出现一次。所以,我相信,你要问的是有多少人有一个B。

如果这是真的,你可以使用HQL来回答你的问题(你也可以使用标准构建器,但我更喜欢hql)。这是一个示例(使用build-test-data插件构建具有buildLazy的对象并向A添加String名称):

def a1 = A.buildLazy(name: "one")
def a2 = A.buildLazy(name: "two")
def a3 = A.buildLazy(name: "three")
def a4 = A.buildLazy(name: "four")

def b1 = B.buildLazy(code: 888)
def b2 = B.buildLazy(code: 999)

a1.addToBs(b1)
a2.addToBs(b1)
a3.addToBs(b1)
a4.addToBs(b1)

a1.addToBs(b2)

println "Number of As that have each B = " + 
    A.executeQuery("select count(b), b.code from A as a join a.bs as b group by b.code")

println "Number of As with a specific B = " + 
    A.executeQuery("select count(*) from A as a join a.bs as b where b = :b", [b: b1])

结果:

Number of As that have each B = [[1, 999], [4, 888]]
Number of As with a specific B = [4]