我如何排序的属性在Grails的可为空的关联? [英] How do I sort by a property on a nullable association in Grails?
问题描述
我想排序数据表。我有以下域(转述和榜样,指明分数):
I'm trying to sort a table of data. I have the following domain (paraphrased and example-ified):
class Car {
Engine engine
static constraints = {
engine nullable: true // poor example, I know
}
}
class Engine {
String name
}
下面是一个的处理排序控制器动作:
Here's the controller action that's handling the sort:
def myAction = {
def list = Car.findAll(params)
render(view: 'list', model: [list: list])
}
我提供了一些数据,有几辆车,有的用空引擎和其他与引擎不为空。
I provision some data such that there are several Cars, some with null engines and others with engines that are not null.
我尝试以下查询:
http://www.example.com/myController/myAction?sort=engine.name&order=asc
从查询结果只返回其发动机不为空汽车的条目。这是的不同的的防止可能,如果我只是查询该协会将退还(不计其财产)的结果:
The results from the query only return Car entries whose engine is not null. This is different from the results that would be returned if I only queried the association (without its property):
http://www.example.com/myController/myAction?sort=engine&order=asc
这将返回所有轿车结果,与空引擎的人组合在一起。
which would return all of the Car results, grouping the ones with null engines together.
有什么方法是:
- 我可以得到的排序由关联属性返回相同的结果进行排序只由协会之一(另外两个组合在一起的空关联)? 查询
- 我可以使用取得这些成果内置排序传递到
的list()
(即不使用标准或HQL查询)
- I can get the query that sorts by the association property to return the same results as the one that sorts by only the association (with the null associations grouped together)?
- I can achieve those results using the built-in sorting passed to
list()
(i.e. without using a Criteria or HQL query)
推荐答案
您需要在查询指定LEFT_JOIN,试试这个:
You need to specify LEFT_JOIN in the query, try this:
import org.hibernate.criterion.CriteriaSpecification
...
def list = Car.createCriteria().list ([max:params.max?:10, offset: params.offset?:0 ]){
if (params.sort == 'engine.name') {
createAlias("engine","e", CriteriaSpecification.LEFT_JOIN)
order( "e.name",params.order)
} else {
order(params.sort, params.order)
}
}
记住把engine.name的财产在你的list.gsp命令由
Remember to put engine.name as the property to order by in your list.gsp
<g:sortableColumn property="engine.name" title="Engine Name" />
这篇关于我如何排序的属性在Grails的可为空的关联?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!