Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to order by more than one field in Grails?

Is there a way to get a list ordered by two fields, say last and first names?

I know .listOrderByLastAndFirst and .list(sort:'last, first') won't work.

like image 963
TheBrain Avatar asked Nov 28 '08 15:11

TheBrain


4 Answers

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')
    }
}
like image 127
mattlary Avatar answered Nov 11 '22 12:11

mattlary


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')
    }
}
like image 11
Arnar B Avatar answered Nov 11 '22 11:11

Arnar B


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")
}
like image 8
Hates_ Avatar answered Nov 11 '22 11:11

Hates_


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

like image 5
chim Avatar answered Nov 11 '22 11:11

chim