开发者

Grails GORM self-referential belongsTo deletes opposite direction from expected

开发者 https://www.devze.com 2023-02-20 17:24 出处:网络
I have a Grails domain class that is a hierarchy of categories.Each Category has a parent category (except for the root category which is null).

I have a Grails domain class that is a hierarchy of categories. Each Category has a parent category (except for the root category which is null).

class Category {
    String name

    static mapping = {
        cache true
        name index:'category_name_idx'
    }

    static belongsTo = [parent:Category]

    static constraints = {
        parent(nullable:true)
    }
}

My problem: deletes cascade exactly opposite of what I'd expect:

  • someSubCategory.delete() deletes the category then tries to delete the parent category (which fails with an integrity violation if the parent has other children).
  • parentCategory.delete() does NOT cascade delete its children, but instead just fails w开发者_如何学Pythonith an integrity violation.

What am I doing wrong? My understanding is that the 'belongsTo' above should tell the GORM to cascade deletes from the parent to all children, but not from a child to its parent.


If I am understanding correctly a Category belongs to a parent and a parent can have multiple children, so I think you need a hasMany relationship, something like this:

class Category {
    String name

    static mapping = {
        cache true
        name index:'category_name_idx'
    }

    static belongsTo = [parent:Category]
    static hasMany = [children: Category]

    static constraints = {
        parent(nullable:true)
    }
}

I had had similar structures and never have issues with the delete doing it this way.

Hope this helps!


It's not an answer, but I found a workaround to my own question. You can remove the belongsTo = [parent:Category], replacing it with a simple instance variable. This stops subCategory.delete() from cascading to the parent.

class Category {
    String name
    Category parent

    static mapping = {
        cache true
        name index:'category_name_idx'
    }

    static constraints = {
        parent(nullable:true)
    }
}
0

精彩评论

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