Defining default sort-order in Grails/GORM

后端 未结 3 1793
礼貌的吻别
礼貌的吻别 2021-02-19 02:08

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 sor

相关标签:
3条回答
  • 2021-02-19 02:25

    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'
        }
    }
    
    0 讨论(0)
  • 2021-02-19 02:35

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

    • Grails 1.1 release notes (search for "Default Sort Order")
    0 讨论(0)
  • 2021-02-19 02:47

    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"]
    }
    
    0 讨论(0)
提交回复
热议问题