仅出于背景考虑,让我们拥有以下三个域类:
class Group {
Long id
Person person
}
class Person {
Long id
Country country
String name
}
class Country {
Long id
}
因此,考虑到这些类,为我提供了一个Group对象的ID以及一个Country对象的ID。我想基于这两个获得Person对象的列表。
看起来相对简单,但是我不熟悉标准查询,因此我很难弄清楚自己在做什么错。这是我到目前为止所拥有的:
def c = Group.createCriteria()
def names = c.list (order: "asc") {
createAlias('person', 'p')
createAlias('p.country', 'c')
and {
eq ('c.id', Long.valueOf(countryId))
eq ('id', groupId)
}
projections {
property('p.name')
}
}
当然,这是错误的,因为它会引发错误。有人可以让我知道我做错了吗?
谢谢你的帮助!
最佳答案
static def searchPersons(Map params) {
return Group.createCriteria().list(params, {
if(params.groupId) {
eq('id', params.groupId.toLong())
}
person {
order('name')
if(params.countryId) {
country {
eq('id', params.countryId.toLong())
}
}
}
projections {
property('person')
}
})
}
不过,最好在您的域上添加必要的关联(hasMany等)。
关于grails - 如何编写涉及三个域的相对简单的条件查询?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32406998/