如何计算 gorm - grails 中一对多关系的出现次数
我有2个域类
class A {
....
static hasMany = [bs:B]
}
class B {
int code
....
}
如何列出B中所有代码在所有A表中出现的次数?
一样的东西
b.each { thisb ->
int ocurrences = A.bs.findAll{it == thisb}.size()
...
}
像谢谢
I have 2 domain classes
class A {
....
static hasMany = [bs:B]
}
class B {
int code
....
}
How can I list the number of ocurrences of all codes in B in all the A table?
Something like
b.each { thisb ->
int ocurrences = A.bs.findAll{it == thisb}.size()
...
}
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为我对这个问题有点困惑的原因是,从技术上讲,它实际上是一种多对多关系,而不是真正的一对多关系。 Grails 将为该关系创建一个连接表(“a_b”)(因为 B 与 A 没有“belongsTo”关系)。
A 域构造 hasMany 关系的方式是一个集合,因此 B 只会在“bs”集合中出现一次。所以,我相信,您所问的只是有多少个 A 有 B。
如果这是真的,您可以使用 HQL 来回答您的问题(您也可以使用标准构建器,但我更喜欢 hql)。这是一个示例(使用 build-test-data 插件使用 buildLazy 构造对象并向 A 添加字符串名称):
结果:
I think the reason that I'm a little confused by this question is that technically it's actually a many-to-many relationship, not really a one-to-many. Grails will create a join table ("a_b") for this relationship (because B doesn't have a belongsTo relationship to A).
The way you have your A domain constructed the hasMany relationship is a set, so B will only appear a single time in the "bs" collection. So, I believe, all you're asking is how many As have a B.
If thats true, you can use HQL to answer your question (you can also use criteria builders, but I prefer hql). Here's an example (using the build-test-data plugin to construct objects with buildLazy and adding a String name to A):
results in: