3

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

codeBarer
  • 2,238
  • 7
  • 44
  • 75

1 Answers1

5

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.

Gregg
  • 34,973
  • 19
  • 109
  • 214
  • I like the grailsier way :). Is there options of sorting desc vs. asc? – codeBarer Jan 08 '14 at 19:38
  • 1
    [Docs say you can](http://grails.org/doc/latest/ref/Database%20Mapping/sort.html), _sort varName: "asc"_ or _sort varName: "desc"_ – Hernán Erasmo Jan 08 '14 at 20:20
  • For some reason the sorting is not working on the controller nor on the domain class. Is this a known problem? Everytime I do a refresh the order keeps changing. – codeBarer Jan 13 '14 at 20:46