17

Let's say I have definied a User object using GORM. Each user can have zero or more Login:s. Each Login has a timestamp. When retrieving user.logins I want the logins to be sorted based on the value of login.date. What is the correct Grails way to achieve this?

Example: I want the following code to list all the user's logins in ascending order.

<g:each var="login" in="${user.logins}">
  <tr>
    <td>${login.date}</td>
  </tr>
</g:each>

These are the referenced classes:

class User {
  ...
  def hasMany = [logins: Login]
  static fetchMode = [logins: "eager"]
}

class Login {
  Date date
  ...
  def belongsTo = [User]
}

I'm running Grails 1.0.4 which is the latest stable release.

knorv
  • 49,059
  • 74
  • 210
  • 294

3 Answers3

30

They show how to do this on the GORM page in the reference guide (section 5). The bit you want is near the bottom of that document is the section you want. They have two simple examples:

class Airport {
    …
    static mapping = {
        sort "name"
    }
}

class Airport {
    …
    static mapping = {
        sort name:"desc"
    }
}

They also have an example of sorting on an association:

class Airport {
    …
    static hasMany = [flights:Flight]
    static mapping = {
        flights sort:'number'
    }
}
Jason Plank
  • 2,336
  • 5
  • 31
  • 40
  • 2
    And if you want descending on association: `flights sort:'number', order: 'desc'` (per http://grails.1312388.n4.nabble.com/sort-by-association-descending-td1312425.html) – Jeff Allen Apr 16 '13 at 01:27
  • 1
    How can I sort multiple attributes? – ricardogobbo Dec 08 '15 at 17:42
  • 1
    @ricardogobbo Might be a tad late, but here you go: `static mapping = { sort([column1: 'asc', column2: 'asc']) }` – Gideon Jul 05 '18 at 07:46
14

Just make the Login Class implement the Comparable interface:

class Login implements Comparable {

    // ...

    Date date

    public int compareTo(def other) {
        return date <=> other?.date // <=> is the compareTo operator in groovy
    }

}

and declare the relation to be a SortedSet:

class User {
  ...
  def hasMany = [logins: Login]               
  SortedSet logins

  static fetchMode = [logins: "eager"]
}
tjg184
  • 4,508
  • 1
  • 27
  • 54
Siegfried Puchbauer
  • 6,539
  • 34
  • 24
8

The handling of default sort order in Grails/GORM seems to have been radically simplified in Grails 1.1:

knorv
  • 49,059
  • 74
  • 210
  • 294