使用hasmany字符串查询Grails / GORM标准 [英] Grails / GORM criteria query with hasmany String
问题描述
class Cat {
字符串名称
static hasMany = [
nicknames:String
]
}
(一只猫有一个名字,并且有很多昵称(即字符串))
我试图用某些昵称来查询所有的猫。
我试过这个:
PagedResultList getCatsByNickname(String昵称,Map params){
PagedResultList results = Cat.createCriteria()。list(params){$ b $'ilike'('nicknames','%'+ nickname +'%')
}
返回结果
}
但它永远不会返回任何结果。 (如果我将查询更改为使用简单名称属性,它可以找到具有该名称的所有猫,但我想查询昵称。)
我也试试这个:
$ b $ pre $ PagedResultList getCatsByNickname(String昵称,Map params){
PagedResultList结果= Cat.createCriteria()。 list(params){
'昵称'{
'ilike'('昵称','%'+昵称+'%')
}
}
返回结果
}
但是我得到错误:org.hibernate.MappingException:集合不是关联:example.Cat.nicknames
所以问题是,我如何查询一个hasMany类型的String?
经过大量的尝试和研究后,我发现这将适用于Grails 2.4.0,我不知道旧版本。
Cat.withCriteria {
createAlias('nicknames','n')
ilike'n.elements','%kitty%'
}
诀窍在于使用'n。元素'
I have a domain object (Cat) like this:
class Cat {
String name
static hasMany = [
nicknames: String
]
}
(A cat has a name, and also has many nicknames (which are Strings))
And I am trying to query all the cats with certain nicknames.
I've tried this:
PagedResultList getCatsByNickname(String nickname, Map params) {
PagedResultList results = Cat.createCriteria().list(params) {
'ilike'('nicknames','%'+nickname+'%')
}
return results
}
But it never returns any results. (If I change the query to just use the simple name attribute, it works finding all cats with that name, but I want to query against the nicknames.)
I also tried this:
PagedResultList getCatsByNickname(String nickname, Map params) {
PagedResultList results = Cat.createCriteria().list(params) {
'nicknames' {
'ilike'('nicknames','%'+nickname+'%')
}
}
return results
}
But I get the error: org.hibernate.MappingException: collection was not an association: example.Cat.nicknames
So the question is, how do I query against a hasMany of type String?
After a lot of trying and researching, I found this will work with Grails 2.4.0, I don't know about older versions.
Cat.withCriteria {
createAlias('nicknames', 'n')
ilike 'n.elements', '%kitty%'
}
The trick is to use 'n.elements'
这篇关于使用hasmany字符串查询Grails / GORM标准的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!