views:

42

answers:

3

Is it possible in grails to sort query results according to a property of a parent class in a relationship. E.g. I have a user domain class which has a one to many relationship with a list of Tasks.

When showing the list page of the Tasks domain class, I want to be able to sort the list of tasks by the associated User name.

class User {
    String name
    String login
    String group
    List tasks = new ArrayList()
    static hasMany = [tasks:Task]
}

class Task {
    String summary
    String details
    User user
    static belongsTo = [user:User]
}

I can do something like this

Task.list([sort:"user", order:"asc"])

But this sorts by the user.id, is there a way to specify the sort to be on the user.name?

A: 

I would look into giving User a default sort order and implement Comparable. Grails may work under the covers differently to what I would expect though and there may be a simple alternative that I'm not aware of.

Michael Rutherfurd
Looks like Aaron Saunders criteria implementation should do the job
Michael Rutherfurd
+2  A: 

You can do it using Criteria

def criteria = Task.createCriteria()
def taskList = criteria.list {
    createAlias("user","_user")
    order( "_user.name")
}
Aaron Saunders
Cool, works like a charm. Any idea how I can make the sorting case insensitive?
omarello
Never mind, found it on hibernate docs, apparently i just add .ignoreCase() to the order like thisorder("_user.name").ignoreCase()
omarello
A: 

iirc, grails sorts by using toString() and since you have not supplied one, it uses the id.

Ray Tayek