Grails 在find中调用contains()方法

Grails 在find中调用contains()方法,grails,gorm,grails-2.0,Grails,Gorm,Grails 2.0,我有以下域结构: class Emloyee { static hasMany = [users: User] ..... } 我想编写一个方法 从拥有该用户的员工中删除该用户 删除用户 我的代码如下所示: def deleteUser(User userInstance) { def employee = Employee.find { users.contains(userInstance) } employee .removeFromUsers(userI

我有以下域结构:

class Emloyee {

  static hasMany = [users: User]
  .....  

}
我想编写一个方法

  • 从拥有该用户的员工中删除该用户
  • 删除用户
  • 我的代码如下所示:

    def deleteUser(User userInstance) {
        def employee = Employee.find { users.contains(userInstance) }
        employee .removeFromUsers(userInstance)
        employee .save(flush: true, failOnError: true)
        userInstance.delete(flush: true, failOnError: true)
    }
    
    这段代码给了我一个例外:

    No signature of method: grails.gorm.DetachedCriteria.contains() is applicable for argument types: (User)
    

    我做错了什么?谢谢大家!

    一个用户是否总是包含一名员工

    然后您可以使用

    static belongsTo = [employee: Employee]
    
    在用户域类中。在这种情况下,您不需要从employee域手动删除用户。GORM在调用userInstance.delete(…)时删除它

    如果您不想使用belongsTo,可以通过以下方式删除用户:

    def deleteUser(User userInstance) {
        def c = Employee.createCriteria()
        def result = c.get {
            users {
                idEq(userInstance.id)
            }
        }
        result.removeFromUsers(userInstance)
    
        userInstance.delete(flush: true, failOnError: true)
    }
    
    希望这有帮助。 Sven

    这里有一个解决方法: