删除m-to-m也试图级联删除一对二

时间:2010-10-09 16:59:00

标签: grails gorm

我有以下域名

class Committee {
   String name
   BoardCommitteeType boardCommitteeType
   Date dateCreated
   Date lastUpdated
   User createdBy
   User modifiedBy

   static belongsTo = [
      board: Board,
   ]

   static hasMany = [          
      members: User
   ]
}

class User {

    static hasMany = [            
        committees: Committee,     
    ]

    static belongsTo = [
        Board, Committee
    ]
}

问题在于,当我尝试做一个board.removeFromCommittees(委员会)时,我得到以下例外:

删除的对象将通过级联重新保存(从关联中删除已删除的对象):[com.wbr.highbar.User#1];

我明白这意味着什么。我不明白的是为什么我得到它。另一个有趣的是,如果我在委员会实例null中创建creatdBy和modifiedBy,则删除工作正常。这就是为什么我认为GORM正在尝试级联一对二的。我的理论是,这与用户属于委员会的事实有关。但我不知道如何解决这个问题。

1 个答案:

答案 0 :(得分:0)

级联删除受域类之间的belongsTo关系影响。

Committee belongsTo Board以来,当董事会被删除时,删除级联到委员会。从User belongsTo Committee开始,当委员会被删除时,删除级联到用户。

问题的解决方案是删除User belongsTo Committee关系。

关于您的域名模型的整体说明:

你有很多多对多的关系。它们不一定是错的,但它们可能会使事情过于复杂。你可能只是使用:

class Committee {
    static hasMany = [boards: Board, users: User]
}

class Board {
    static hasMany = [users: User]
    static belongsTo = Committee // this is the only belongsTo you need, since if a
                                 // committee is dissolved, presumably the board
                                 // will be dissolved as well (unless you have
                                 // cross-committee boards)
}

class User {
    // doesn't define any relationships,
    // let the Committee/Board domains handle everything

    // also, this is presuming that users are at a higher level than committees, i.e.
    // a user could belong to multiple committees
}