1
votes

I do not have too much expierence in Grails, so maybe I do not understand hasMany and belongsTo relations in GORM.

Say, I have 2 classes Parent.groovy and 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)

Now I want to change a parent of a child

child1.parent = parent2 // no effect
child1.save(flush: true)

In controller it is possible

Child child1 = Child.get(1)
bindData(child1, [parent: [id: 2]])
child1.save(flush: true)

But now there is null in movie1.children, in DB I can see that parent_id has changed to 2

Note: In Active Record (Rails) it is easy

child1.parent_id = 2

Maybe I do not need to use such relation if I want to change parent?

Maybe there is another way to do it?

1

1 Answers

0
votes

After some investigation I understood why there is a null in collection. At the very beginning there are such values in Child table

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

After

bindData(child1, [parent: [id: 2]])

We have

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

So now parent2 has child1 with parent_idx 0 - it is ok. But parent1 has child2 with parent_idx = 1 (without 0). So we changed parent_id value without changing parent_idx.

I wish there was a possibility to change index in collection too. So the conclusion is:

I we want to change parent we should not use List collection, so we will not have idx column and no problems