[英]Uniary Relationship on Grails GORM
Based this GORM Domain class: 基于此GORM域类:
class Component implements Serializable {
Long id
String name
Double total
Long parentComponentId
static mapping = {
...
}
static constraints = {
...
parentComponentId nullable: true
}
}
My questions are: 我的问题是:
parentComponentId
is another instance of Component
. 我们如何引用Domain类本身,在这种情况下, parentComponentId
是Component
另一个实例。
select a.*, b.* from COMPONENT a join COMPONENT b on a.id = b.parentComponentId group by a.id having sum(b.total) = a.total
Just change the Long parentComponentId
to Component parentComponent
. 只需将Long parentComponentId
更改为Component parentComponent
。 You also don't need the Long id
property, as grails add it for you: 您也不需要Long id
属性,因为grails为您添加了它:
class Component implements Serializable {
String name
Double total
Component parentComponent
static constraints = {
parentComponent nullable: true
}
}
Then you can access both the parent component and the parent component id: 然后,您可以访问父组件和父组件ID:
assert Component.read(1).parentComponentId == Component.read(1).parentComponent.id
If you want to have cascade deletes, you'll need to remove the parentComponent property and add: 如果要进行级联删除,则需要删除parentComponent属性并添加:
static hasMany = [nestedComponents: Component]
static belongsTo = [parentComponent: Component]
I'm assuming you have a 0:N
relationship, if not you'll need to change that. 我假设您的关系为0:N
,否则,您需要进行更改。 Check the documentation for defining associations . 检查文档以定义关联 。
As for your second question, sadly you can't use having
in a criteria yet: https://jira.grails.org/browse/GRAILS-7880 至于你的第二个问题,遗憾的是你不能使用having
在标准尚未: https://jira.grails.org/browse/GRAILS-7880
You can do it with HQL though: 您可以使用HQL做到这一点:
Component.executeQuery("""
select parent from Component parent, Component nested
where nested.parentComponent = parent
group by parent
having parent.total = sum(nested.total)
""".toString())
You can do like this for first question. 对于第一个问题,您可以这样做。
class Component implements Serializable {
Long id
String name
Double total
static belongsTo = [parentComponentId:Component]
static mapping = {
...
}
static constraints = {
...
parentComponentId nullable: true
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.