Tuesday, May 18, 2010

GORM Criteria using child to parent relationship

I was surprised that I couldn’t find an example of this in any of the Grails and GORM docs or online examples.

I want to find the names and number of occurrences of the CHILD in a 1 to many association based on an attribute in the parent.

The domain classes are:

class Parent {
static hasMany = [children:Child]
String firstname
}

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

}

To find all the children and # of occurrences across ANY Parent where firstname is 'John':

def fName = 'John'
def children = Parent.withCriteria {
projections {
groupProperty 'name'
count 'id'
}
parent {
eq 'firstname', fName
}

}