Dean Moses
Dean Moses

Reputation: 2382

Grails GORM self-referential belongsTo deletes opposite direction from expected

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:

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.

Upvotes: 3

Views: 2282

Answers (2)

Maricel
Maricel

Reputation: 2089

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!

Upvotes: 6

Dean Moses
Dean Moses

Reputation: 2382

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)
    }
}

Upvotes: 1

Related Questions