Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort a collection in grails by date

Tags:

grails

I am wanting to sort a collection in grails by date I am currently doing the following:

def pics = Picture.findAllByChild(child, [sort: 'dateCreated', order: 'desc'])
pics.add(Post.findAllByPostedToAll(true))

Because I have added more items to the list i need to sort again by dateCreated descending It doesn't look like the sort class can do this. I have tried:

pics.sort(it.dateCreated)

But this is not allowed

like image 414
Sagarmichael Avatar asked Sep 18 '12 18:09

Sagarmichael


2 Answers

the sort method takes a closure argument, so the correct call (with implicit parens) is

pics.sort { it.dateCreated }
like image 171
doelleri Avatar answered Oct 21 '22 22:10

doelleri


You can also change the default sort on the association.

In your Picture domain class add:

static mapping = { 
    child(sort:'dateCreated', order:'desc')
}

This is not supported for unidirectional one to many relationships, but works great for bidirectional ones.

like image 39
Jay Prall Avatar answered Oct 21 '22 23:10

Jay Prall