Sorting query results according to parent property in grails

余生长醉 提交于 2019-12-23 01:21:49

问题


Is it possible in grails to sort query results according to a property of a parent class in a relationship. E.g. I have a user domain class which has a one to many relationship with a list of Tasks.

When showing the list page of the Tasks domain class, I want to be able to sort the list of tasks by the associated User name.

class User {
    String name
    String login
    String group
    List tasks = new ArrayList()
    static hasMany = [tasks:Task]
}

class Task {
    String summary
    String details
    User user
    static belongsTo = [user:User]
}

I can do something like this

Task.list([sort:"user", order:"asc"])

But this sorts by the user.id, is there a way to specify the sort to be on the user.name?


回答1:


You can do it using Criteria

def criteria = Task.createCriteria()
def taskList = criteria.list {
    createAlias("user","_user")
    order( "_user.name")
}



回答2:


iirc, grails sorts by using toString() and since you have not supplied one, it uses the id.



来源:https://stackoverflow.com/questions/3594301/sorting-query-results-according-to-parent-property-in-grails

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!