grails: sort by nested attributes

2019-02-13 16:50发布

Is it possible to sort by nested attributes using where queries?

I have 2 domain classes:

class Parent {
    String name
    Child child
}

and

class Child {
    String name
    static belongsTo = [parent: Parent]
}

This works:

Parent.where {}.list(sort: 'name')

and this doesn't:

Parent.where {}.list(sort: 'child.name')

I have an error:

could not resolve property: child.name of: Parent

I am using grails 2.3.x

标签: grails gorm
1条回答
时光不老,我们不散
2楼-- · 2019-02-13 17:24

See this: Grails - sort by the domain relation attribute (using createCriteria())

Solution 1:

    def criteria = Child.createCriteria();
    println criteria.list{
        createAlias("parent","_parent")
        order( "_parent.name")
    }

Solution 2:

    def criteria = Child.createCriteria();
    println criteria.list{
        parent {
            order("name")
        }
    }

Solution 3:

class Child {
    String name
    static belongsTo = [parent: Parent]

    public String getParentName(){
        return parent.getName()
    }
}

println Child.listOrderByParentName()

Hope it helps.

查看更多
登录 后发表回答