Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

grails: sort by nested attributes

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

like image 463
user3718614 Avatar asked Jun 08 '14 09:06

user3718614


1 Answers

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.

like image 87
André Augusto Costa Santos Avatar answered Dec 08 '22 12:12

André Augusto Costa Santos