0
votes

I have a grails domain hasMany and belongsTo relationship as the below :

I am wanting to sort based on 'Submission' 'lastUpdated' 'desc'

class User {
  String username
  String password

  static hasMany = [ submissions: Submission ]

  static mapping = {
     sort submissions: 'desc'  // This doesn't do anything?
  }
}

class Submission {
  String reference
  Date dateCreated
  Date lastUpdated

  static belongsTo = User
}

So everytime I collect a User's submissions, I would like it default sorted as lastUpdated desc. The equivalent mysql statement would be the following

select (fields) from submission order by last_updated desc;

Am i missing something?

Thanks greatly!

2

2 Answers

0
votes

Because this is a unidirectional relationship, the following solution works perfectly!

class User {
  String username
  String password

  SortedSet submissions

  static hasMany = [ submissions: Submission ]

}

class Submission implements Comparable {
  String reference
  Date dateCreated
  Date lastUpdated

  static belongsTo = User

  @Override
  public int compareTo(obj) {
        obj.lastUpdated.compareTo(lastUpdated)
  } 

}
0
votes

I think you should read how to set default sort order in assosiation

From GORM documentation

Finally, you can configure sorting at the association level:

class Airport {
    ...
    static hasMany = [flights: Flight]

    static mapping = {
        flights sort: 'number', order: 'desc'
    }
}