How to order by more than one field in Grails?

為{幸葍}努か 提交于 2019-11-28 17:47:40
Hates_

This old solution no longer works. Please see mattlary's answer below

You may have to write a custom finder in HQL or use the Criteria Builder.

MyDomain.find("from Domain as d order by last,first desc")

Or

def c = MyDomain.createCriteria()
def results = c.list {
       order("last,first", "desc")
}
mattlary

Hates_ criteria answer didn't seem to work for me; putting "last,first" in order will only cause exceptions saying, "Property 'last,first' not found". To order on two fields, you can do the following:

def c = MyDomain.createCriteria()
def results = c.list {
    and{
       order('last','desc')
       order('first','desc')
    }
}

This is quite old but helped me in finding a suitable solution. A "cleaner" code example by using withCriteria shortcut:

def c = MyDomain.withCriteria {
    and {
        order('last', 'desc')
        order('first', 'desc')
    }
}

More complicated ordering criteria, (tested in Grails 2.1.0)

def c = MyDomain.withCriteria {
    property {
        order('last', 'desc')
    }
    order('first', 'desc')
}

sorts first by MyDomain.property.last then by MyDomain.first

Nakul

This query is working on the basis of first field. When the first field is blank then it is shorted by the second field.

order('last','desc')
order('first','desc')

I think a criteria is the best bet, but you did the right thing by attempting a finder first. When retrieving domain objects from GORM, the right order to make the attempt is: dynamic finder, criteria, HQL.

maq

you can do this

def results=MyDomain.findAll([sort:"last",order:'desc'],[sort:"first",order:'desc']);

this line of code will first sort results from domain class "MyDomain" first by last name and then by first name of the person .

MyDomain.findAll(sort: ['first': 'desc','last':'desc'])

works with grails-datastore-gorm:6.0.3

If you were sorting lists on the contents of their items, you would need to implement a comparator which would have some smarts to enable to you decide the sort order based on multiple properties.

Some examples of Groovy-style comparators are shown here

However if the list you are sorting is being returned from a database query, you would be better off sorting it using a CrteriaQuery and sorts on that

I has the same problem. Since my list is not so big, I use groovy sort, as I want to sort on fields of linked domain: CalendarData -> Attraction

def listCalendar (Calendar calendar) {
    respond CalendarData.where {
        calendar == calendar
    }.list().sort{ "$it.attraction.type?:' '$it.attraction.name" }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!