域支出:
class User {
String username
static hasMany = [userRoles: UserRole]
}
class Role {
String authority
}
class UserRole {
User user
Role role
static belongsTo = [User, Role]
}
这是安装grails spring-security-core插件时通常会找到的压缩版本。
现在,一个用户可以拥有多个角色。因此,管理员可以是普通用户。用户:UserRole = 1:M
在SQL中,很容易获得没有附加用户角色的一组用户。
用Grails条件构建器如何做到这一点?
作为一个固定的解决方法(直到我得到一个很好的答案,即基本上没有将SQL插入Grails中),我基本上将所有管理员用户作为一个集合,然后将用户列表作为另一个,然后一对一地删除所有管理员用户退出。丑陋,但是(缓慢)起作用:
def existing = UserRole.createCriteria().listDistinct {
eq("role",adminRole)
}.collect{it.user} as Set
def f = User.createCriteria().listDistinct {
userRoles {
ne("role",adminRole)
}
}.collect{it} as Set
existing.each { ex ->
f.each { non ->
if (non.id == ex.id) {
f.remove(non)
}
}
}
在上面的代码中,如果执行f.removeAll(existing),将无法正常工作。
我认为这是一个很好的答案,因为您也可以将其应用于其他情况。
提前致谢!
最佳答案
我不确定如何使用条件查询来执行此操作,但是此HQL可以工作:
def role = ...
def usersWithoutRole = UserRole.executeQuery(
'from User u where u not in ' +
'(select ur.user from UserRole ur where ur.role=:r)',
[r: role])
关于grails - 使不在其他结果集中查找(或在Spring中查找非管理员用户)的Grails标准,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8961041/