我有两个域类CGroup和Directory,我想建模一个包含许多目录的CGroup,但是其中一个目录被称为“根”,并且可以从CGroup直接访问。任何CGroup都应该只有一个根。,级联仍然可以工作,以至于删除任何目录都会删除它的所有子目录。
虽然我错了,但到目前为止,这就是我所拥有的:
class CGroup{
...
Directory root
static hasMany = [directory:Directory]
static constraints = {
root(unique:true)
}
}
class Directory {
static hasMany = [children:Directory]
...
static belongsTo = [parent:Directory,
cgroup:CGroup]
static constraints = {
parent nullable: true
}
}
基本上,我只需要引用存储在" one“端的”多“集合中的一个实例。
发布于 2016-03-31 21:17:49
我尝试了几种不同的方法,唯一能让它工作的方法是允许root
暂时为空。我没有这样做的问题是由于排序--因为Directory
实例在hasMany
中,所以在保存CGroup
之前不能保存它们,或者因为cgroup
为null (调用addToDirectory
时设置),所以CGroup
()调用将失败。但是,如果CGroup不能为空,则在不设置其root
属性的情况下无法保存它。
因此,我使root
为空,但添加了一个自定义验证器,如果root
为null,并且hasMany
中有任何实例,该验证程序就会失败。
static constraints = {
root nullable: true, validator: { Directory root, CGroup cgroup ->
if (!root && cgroup.directory?.size()) {
return ['root.required']
}
}
}
因此,您将使用任何必需的值保存CGroup
实例,而不使用任何关联的Directory
实例。然后将Directory
实例与addToDirectory
连接起来,并使用自定义setter设置root
实例:
void setRoot(Directory root) {
if (this.root) {
removeFromDirectory this.root
}
if (root) {
addToDirectory root
}
this.root = root
}
再保存一次:
def group = new CGroup(...).save()
group.root = new Directory(...)
group.addToDirectory(new Directory(...))
group.addToDirectory(new Directory(...))
group.save()
g1.errors
https://stackoverflow.com/questions/36347371
复制相似问题