Sort a Grails Domain list using a column index instead of column name

435 views Asked by At

I retrieve rows on the my database through my domain using a code similar to this:

def DomainList = DomainClass.list(sort: orderBy, order: "asc")

Assuming that the orderBy variable is a String that is the name of one of the domain's column. But what if I want to sort it by a column index instead:

SELECT * FROM `table` ORDER BY 2 DESC

How can I do that on Grails?

1

There are 1 answers

0
Gideon On BEST ANSWER

After some time, I gave up on finding a dynamic solution. Instead, I use an if-else trap at the beginning of the code since each index corresponds to a particular column:

def orderBy = params?.orderBy
def orderByPolicy = params?.orderByPolicy

if(orderBy.equals("0")) {
    orderBy = "name_of_index_0_column"
}
else if(orderBy.equals("1")) {
    orderBy = "name_of_index_1_column"
}
else if(orderBy.equals("2")) {
    orderBy = "name_of_index_2_column"
}
else if(orderBy.equals("3")) {
    orderBy = "name_of_index_3_column"
}

if(!orderByPolicy?.equalsIgnoreCase("desc")) {
    orderByPolicy = "asc"
}

def DomainList = DomainClass.list(sort: orderBy, order: orderByPolicy)

Note though, this is not dynamic. It cannot accommodate adding on new columns to the DomainClass; you must manually edit also the if-else trap.