سؤال

In my domain I have a many-to-many relationship. The problem is that GORM forces me to define owner entity but I don't think that either side "owns" the relation.

class User {    
    String username
    String password

    static hasMany = [organizations: Organization]
    static belongsTo = Organization

    static constraints = {
    }
}


class Organization {
    String name;

    static hasMany = [members: User]
}

In this case I'm obviously not allowed to delete User who is in some organization (because Organization "owns" the relation). I would like to be able to delete both entities and on delete simply remove the relation (row from user_organization table). Is it possible or do I have to write this logic myself (if so, what would be the best way to implement this)?

هل كانت مفيدة؟

المحلول

You are allowed to delete both sides of the relationship, no matter who is the "owner". The belongsTo just applies the proper cascading so you don't have to.

In your example if you want to delete a user you first have to remove the relationship. So, in order to delete a user you do:

organization.removeFromMembers(user)
user.delete()

And if you delete an organization, since it is the "owner", you just don't need to use removeFrom*.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top