Grails 如何在GORM中更改父级?

Grails 如何在GORM中更改父级?,grails,gorm,has-many,belongs-to,Grails,Gorm,Has Many,Belongs To,我在Grails方面没有太多的经验,所以可能我不理解在GORM中有许多和属于关系 比如说,我有两个类:Parent.groovy和Child.groovy class Parent { String name List childen = new ArrayList() static hasMany = [children: Child] } class Child { String name static belongsTo = [parent: Pa

我在Grails方面没有太多的经验,所以可能我不理解在GORM中有许多属于关系

比如说,我有两个类:Parent.groovy和Child.groovy

class Parent {
    String name
    List childen = new ArrayList() 
    static hasMany = [children: Child]
}
class Child {
    String name
    static belongsTo = [parent: Parent]
}
Person person1 = new Person(name: "Person1")
Child child1 = new Child(name: "child1")
Child child2 = new Child(name: "child2")
person1.addToChildren(child1).save(flush: true)
person1.addToChildren(child2).save(flush: true)
Person person2 = new Person(name: "Person2").save(flush: true)
现在我想换一个孩子的父母

child1.parent = parent2 // no effect
child1.save(flush: true)
在控制器中,这是可能的

Child child1 = Child.get(1)
bindData(child1, [parent: [id: 2]])
child1.save(flush: true)
但现在movie1.children中有null,在DB中我可以看到parent_id已更改为2

注意:在活动记录(Rails)中,这很容易

child1.parent_id = 2
如果我想改变父母,也许我不需要使用这种关系


也许还有别的方法吗?

经过一番调查,我明白了为什么集合中有空值。 一开始,在子表中有这样的值

id | name | parent_id | parent_idx 1 | child1 | 1 | 0 2 | child2 | 1 | 1 我们有

id | name | parent_id | parent_idx 1 | child1 | 2 | 0 2 | child2 | 1 | 1 id |姓名|家长|家长| idx 1 |儿童1 | 2 | 0 2 |儿童2 | 1 | 1 现在parent2有了child1和parent_idx 0-没关系。但是parent1有child2,其parent_idx=1(不带0)。因此,我们更改了parent_id值,而没有更改parent_idx

我希望有一个可能性,改变收集索引太多。 因此,结论是:

我想更改父项,我们不应该使用列表集合,这样我们就不会有idx列,也不会有任何问题

id | name | parent_id | parent_idx 1 | child1 | 2 | 0 2 | child2 | 1 | 1