grailscreatecriteria

Sort by property in one-to-many association


I have the following scenario (Domain classes)

class Request { 
    String title                
    List statusUpdates

    static hasMany = [statusUpdates: StatusUpdate]
}

and

class StatusUpdate {

    Date dateCreated
    String statusFrom
    String statusTo
    String notes

    static belongsTo = Request
}

I am currently using createCriteria to implement filtering and basic sorting of Request.

Now I want to get a list of Requests starting from the most recently updated (ordered by the value of the field dateCreated of the last StatusUpdate for the Request)

Any hint?


Solution

  • assuming that every Request has at least one StatusUpdate and slightly changing belongsTo declaration, you could go the other direction:

    class StatusUpdate {
    
        Date dateCreated
        String statusFrom
        String statusTo
        String notes
    
        static belongsTo = [req: Request] // I assume that naming the field "request" would cause whole bunch of weird problems, therefore "req"
    }
    
    StatusUpdate.createCriteria().list() {
        req {
            // your criteria for requests filtering
        }
        projections {
            groupProperty 'req', 'reqAlias'
            max 'dateCreated', 'maxDateCreatedAlias'
        }
        order 'maxDateCreatedAlias', 'desc'
    }.collect { it[0] }