我認爲我有點困惑的這個問題的原因是,在技術上它實際上是一個多一對多的關係,不是一個真正的單太多。 Grails將爲這個關係創建一個連接表(「a_b」)(因爲B與A沒有belongsTo關係)。
您的A域構建hasMany關係的方式是一個集合,因此B只會在「bs」集合中顯示一次。所以,我相信,所有你問的是有多少如同有一個B.
如果這是真的,你可以使用HQL來回答你的問題(你也可以使用條件構建器,但我更喜歡hql)。下面是一個例子(使用編譯 - 測試數據的插件來構建與buildLazy對象,並添加一個字符串名來A):在
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]
我不知道我理解的題。你想計算每個B所屬的數量? – 2010-04-25 01:04:41
感謝您的回覆;我想知道B中有多少次B存在。 – xain 2010-04-25 01:39:03