为什么在property()
上使用createCriteria
时会返回列表而不是对象?如果不把property()
给我整个对象而不是列表? [[1, 'John', 'Tusk'],[2, 'Nila','Hans'],...]
def employees = User.createCriteria().list{
...
projections{
property("id")
property("pd.firstName")
property("pd.lastName")
}
}
def results = []
employees.each{
results << [id: it[0], name: it[1] + " " + it[2]]
}
除了使用
employees.each
之外,还有另一种方法可以像这样将其呈现为JSON:[{"id":10,"name":"Erik Tucker"},{"id":83,"name":"Jimmy Sun"},..]
最佳答案
原因在文档本身内。
A projection is used to change the nature of the results.
使用投影时,结果变成
list
的list
,其中包含投影属性的值,而不是匹配对象实例的列表。这是设计使然,是documented。使用
each
的方法是完全可以接受的。虽然如此,我个人会使用collect
,但结果是相同的。
关于grails - 在createCriteria上使用属性时可以作为对象返回吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30357815/