tags:

views:

1754

answers:

5

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.

A: 

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

j pimmel
+2  A: 

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")
}
Hates_
+1  A: 

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.

Matthew Taylor
+4  A: 

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')
    }
}
mattlary
A: 

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

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

Nakul