Search code examples
grailsgrails-orm

How to order by Date from a child object with Grails?


I'm trying to order a list of MyObject based on a date into MyObject.ChildObject. When I try to do the following I'm getting an error.

List<MyObject> myObjectList = MyObject.createCriteria().list(max: params.max, offset: params.offset) {
            eq('test', test)
            eq('deleted', Boolean.FALSE)
            if (params.sort?.contains(".")) {
                buildSort(params.sort.tokenize("."), params.order, delegate)
            } else {
               order("${params.sort ?: 'childObject.date'}", params.order ?: 'asc')
            }
        }

When I try this, I get

could not resolve property: invoiceTicketDetail.date of: com.test.MyObject. Stacktrace follows:
org.hibernate.QueryException: could not resolve property: childObject.date of: com.test.MyObject
    at grails.orm.PagedResultList.<init>(PagedResultList.java:55)
    at grails.orm.HibernateCriteriaBuilder.createPagedResultList(HibernateCriteriaBuilder.java:230)

How is the best way to do this?

Into ChildObject I have a Date date attribute. And Into MyObject I have a ChildObject childObject attribute.


Solution

  • You can't access childObject.date directly without either an alias for childObject or a sub criteria. Try it with a sub criteria like this:

    List<MyObject> myObjectList = MyObject.createCriteria().list(max: params.max, offset: params.offset) {
                eq('test', test)
                eq('deleted', Boolean.FALSE)
                if (params.sort?.contains(".")) {
                    buildSort(params.sort.tokenize("."), params.order, delegate)
                } else {
                   childObject {
                       order("${params.sort ?: 'date'}", params.order ?: 'asc')
                   }
                }
            }