Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Grails mapping sort on multiple fields :: Groovy sort on multiple map entries

Stumped on this one. In Grails it seems one cannot define a default sort on multiple columns in domain mapping a la static mapping = { sort 'prop1 desc, prop2 asc' }, or { sort([prop1:'desc', prop2:'asc']) }. Only first column gets sorted, lame.

Similarly, when trying to Groovy sort a Grails findAllBy query on multiple columns, the second sort overrides the first.

def list = [[rowNum:2,position:3],[rowNum:1,position:2],[rowNum:3,position:1]]

list.sort{it.rowNum}.sort{it.position}

Obviously missing the boat on the latter case, the groovy sort. I have seen postings re: implementing comparable, but looking for something more concise if possible.

like image 702
virtualeyes Avatar asked Feb 03 '11 05:02

virtualeyes


2 Answers

Here is a Groovy solution. Still essentially implementing a Comparator though.

list.sort { map1, map2 -> map1.rowNum <=> map2.rowNum ?: map1.position <=> map2.position }
like image 112
Peter Niederwieser Avatar answered Oct 14 '22 21:10

Peter Niederwieser


Thanks to the link from GreenGiant, we see that the issue is closed as fixed as of version 2.3.

There is also example code:

static mapping =
    { sort([lastname:'asc', name:'asc']) }

It is working for me in 2.4.3

like image 28
CSQ Avatar answered Oct 14 '22 20:10

CSQ