How to order by more than one field in Grails?

前端 未结 10 1959
萌比男神i
萌比男神i 2020-12-13 09:03

Is there a way to get a list ordered by two fields, say last and first names?

I know .listOrderByLastAndFirst and .list(sort:\'last, first\')

相关标签:
10条回答
  • 2020-12-13 09:19

    If you were sorting lists on the contents of their items, you would need to implement a comparator which would have some smarts to enable to you decide the sort order based on multiple properties.

    Some examples of Groovy-style comparators are shown here

    However if the list you are sorting is being returned from a database query, you would be better off sorting it using a CrteriaQuery and sorts on that

    0 讨论(0)
  • 2020-12-13 09:22

    This old solution no longer works. Please see mattlary's answer below

    You may have to write a custom finder in HQL or use the Criteria Builder.

    MyDomain.find("from Domain as d order by last,first desc")
    

    Or

    def c = MyDomain.createCriteria()
    def results = c.list {
           order("last,first", "desc")
    }
    
    0 讨论(0)
  • 2020-12-13 09:27

    This query is working on the basis of first field. When the first field is blank then it is shorted by the second field.

    order('last','desc')
    order('first','desc')
    
    0 讨论(0)
  • 2020-12-13 09:34

    you can do this

    def results=MyDomain.findAll([sort:"last",order:'desc'],[sort:"first",order:'desc']);
    

    this line of code will first sort results from domain class "MyDomain" first by last name and then by first name of the person .

    0 讨论(0)
  • 2020-12-13 09:36

    I think a criteria is the best bet, but you did the right thing by attempting a finder first. When retrieving domain objects from GORM, the right order to make the attempt is: dynamic finder, criteria, HQL.

    0 讨论(0)
  • 2020-12-13 09:39

    More complicated ordering criteria, (tested in Grails 2.1.0)

    def c = MyDomain.withCriteria {
        property {
            order('last', 'desc')
        }
        order('first', 'desc')
    }
    

    sorts first by MyDomain.property.last then by MyDomain.first

    0 讨论(0)
提交回复
热议问题