自定义连接表域的多对多标准

时间:2011-07-14 19:41:50

标签: grails many-to-many gorm criteria-api

给出以下示例域:

class UserRole implements Serializable {
  User user
  Role role
}

class User { 
  Set<Role> getRoles() {
    UserRole.findAllByUser(this).collect { it.role } as Set
  } 
}

class Role { 
  Set<User> getUsers() {
    UserRole.findAllByRole(this).collect { it.user } as Set
}

我无法弄清楚如何构建条件来查找具有给定角色的所有用户。我尝试了以下方法:

def crit = User.createCriteria()
def results = crit.list {
  roles {
    eq('authority', 'ROLE_ADMIN')
  }
}

但是,它说它无法在用户中找到属性“角色”。我需要一个标准的原因是因为在搜索用户时会有其他属性,所以动态查找器不适用于这种情况。

1 个答案:

答案 0 :(得分:3)

如果您的预期结果很小,那么执行此操作可能很容易:

def c = UserRole.createCriteria()
def users = c.list {
    role {
        eq('authority', 'ROLE_ADMIN')
    }
    user {
        // additional user property constraints
    }
}.collect { it.user }

如果你期望得到大量的结果,或者你需要翻页,我不太确定。我会把它扔出去,但我从未尝试过。我不知道你是否可以使用projections { property('association') }并让它发挥作用。

def c = UserRole.createCriteria()
def users = c.list {
    projections {
        property('user') // never tried this, but worth a shot
    }
    role {
        eq('authority', 'ROLE_ADMIN')
    }
    user {
        // additional user property constraints
    }
}

我不认为您在示例中尝试执行的操作会起作用,因为您实际上没有在引用{{1}的UserRole类中定义关系}(即使用UserRole)。

相关问题