Search code examples
grailsgroovygrails-domain-classgrails-controller

Sorting Parent and Child in Grails Controller


Hi I'm trying to perform a sort in a controller of parent and child before rendering a json file but I'm not sure how to go about doing it. Here's what I have (excerpt of original code):

class Parent{
    static hasMany = [children:Child]
    String name
    Date dateCreated
}

class Child {
    static belongsTo = [parent:Parent]
    String name
    Date dateCreated
}

In my controller .groovy file I have :

def list(){
    def result = Parent.listOrderByDateCreated(order: "desc")
    .... more code ....

    withFormat{
        json {render result as JSON}
        xml {render result as XML} 
    }
}

and the above works (parent is sorted by date created) but I'm not sure how can I sort all the children by date created within the list.

Thank you for your help in advance. Also I'm using Grails 2.3.2


Solution

  • One way is to assume you always want the children sorted by the dateCreated. Add the following to your Parent domain:

    static mapping = {
      children sort: 'dateCreated'
    }
    

    Another way would be to do the sort after you've pulled the results:

    def sortedChildren = parent.children.sort { it.dateCreated }
    

    If there is a fancier "grailsier" way to do this via finders or criteria, I do not know.