How do I sort by a property on a nullable association in Grails?

你离开我真会死。 提交于 2019-12-13 11:50:47

问题


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.

I attempt the following query:

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.

Is there any way that:

  • 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)

回答1:


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)
        }
    }

Remember to put engine.name as the property to order by in your list.gsp

<g:sortableColumn property="engine.name" title="Engine Name" />


来源:https://stackoverflow.com/questions/5708735/how-do-i-sort-by-a-property-on-a-nullable-association-in-grails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!