简体   繁体   English

Grails:与String进行一对多关联查找

[英]Grails: find by one-to-many association with String

I have a following domain class: 我有以下域类:

class User {
   static hasMany = [roles:String]
}

I would like to find every user which has role ROLE_ADMIN . 我想找到每个具有角色ROLE_ADMIN用户。 Is there any possibility to do that with dynamic finders? 动态查找器有可能做到这一点吗? user.findAllByRoles('ROLE_ADMIN') seems to give me an error. user.findAllByRoles('ROLE_ADMIN')似乎给我一个错误。

UPDATE: it is quite easy to query association where Class A has a list of class B instances and both A and B are domain classes. UPDATE:这是很容易查询的关联,其中类A具有类的列表B实例和两个AB是域类。 But here class A is a domain class and class B is a simple Java string. 但是这里的类A是域类,而类B是简单的Java字符串。

The code for querying association containing list of another domain objects would look like this: 用于查询包含另一个域对象列表的关联的代码如下所示:

`User.findAll { roles { role_name=='ROLE_ADMIN' } }`

What i am looking for is a way to specify the value of a String, for example: 我正在寻找的是一种指定字符串值的方法,例如:

`User.findAll { roles {THIS_VALUE=='ROLE_ADMIN' }}`

UPDATE 2: as far as i have found it is not possible to use criteria with collections of primitive types. 更新2:据我发现,不可能将条件与原始类型的集合一起使用。 It is possible to use HQL though: 可以使用HQL:

User.findAll("from User a where :roles in elements(roles)",[roles:'ROLE_ADMIN'])

However it is not as usefull as a findAll or where query. 但是,它不如findAllwhere查询有用。 I cannot chain findAll methods so defining other methods that for example: get ROLE_ADMIN users with username like 'xxx' requires rewriting whole HQL query. 我无法链接findAll方法,因此要定义其他方法,例如:使用诸如“ xxx”之类的用户名获取ROLE_ADMIN用户需要重写整个HQL查询。 Maybe it is possible to express above HQL condition in form of a where expression? 也许可以用where表达式的形式表达以上HQL条件?

Maybe you can do something like: 也许您可以执行以下操作:

if you have already a user list (userList) 如果您已经有一个用户列表(userList)

def list = userList.findAll { user -> user.roles =~ 'ROLE_ADMIN' }

Hope this help! 希望有帮助!

I have the same problem How to find records by value in their association property via DetachedCriteria 我有同样的问题, 如何通过DetachedCriteria在其关联属性中按值查找记录

I made some investigation and, as I found, it's impossible. 我进行了一些调查,结果发现这是不可能的。 The GORM DSL itself doesn't have any method to check that value contains in association. GORM DSL本身没有任何方法来检查包含的值。 It conains oly that criterias that are in SQL: AND , OR , IN . 它只能说明SQL中的条件: ANDORIN

But! 但! You can join association as table in criteria Querying by Association Redux 您可以在关联查询中按条件将关联作为表加入表中

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM