开发者

How can a Domain Class cascade 'all-delete-orphan' to a child it has no reference to?

开发者 https://www.devze.com 2023-03-03 05:34 出处:网络
In Grails you can have a child class: class Child { Father father static belongsTo = [Father, Mother] } With two parent classes

In Grails you can have a child class:

class Child {
    Father father
    static belongsTo = [Father, Mother]
}

With two parent classes

class Mother{
}

class Father { 
}

It appears that if I father.delete(), then Grails throws a database error saying that the Father can't be deleted because 开发者_运维知识库the child is still around.

How do I cascade all-delete-orphan the Child if the Father class doesn't have a direct reference to the Child class?


Make it bi-directional using hasMany.

class Mother{
  static hasMany = Child
}
class Father{
  static hasMany = Child
}

Doing this should make the cascading work such that when you delete one of the parents the child will also be deleted.


Peter Ledbrook has a good article that covered this GORM Gotchas Part 2

I couldn't get the belongsTo only part to work, but this works for me:

class Father {
  static hasMany = [children: Child]
}

class Child {
  static belongsTo = [father: Father]
}

void testDeleteItg() {
    def father = new Father().save()
    def child = new Child()
    father.addToChildren child
    child.save()
    def childId = child.id

    father.delete(flush:true)
    assertNull(Child.get(childId))
}
0

精彩评论

暂无评论...
验证码 换一张
取 消