Grails hasMany: find all master records with a child that matches a criteria

David B picture David B · Aug 2, 2012 · Viewed 8.2k times · Source

I have this Grails 2.0.3 project wherein there are two models DomainA and DomainB and both are related to each other by a many-to-many relationship in which DomainB is a child of DomainA.

class DomainA {
  // properties
  static hasMany = [domains: DomainB]
}

class DomainB {
  // properties
  static hasMany = [domains: DomainA]
  static belongsTo = [DomainA]
}

Given this kind of design, I want to query all DomainB wherein there is/are an instance(s) of DomainA following the query set to DomainA.

def domainsList = DomainA.createCriteria().list() {
   // other criterions for the other properties
}
DomainB.createCriteria().list() {
   inList("domains", domainsList)
   // other criterions for the other properties
}

When executing the code above, an error is prompt ERROR util.JDBCExceptionReporter - Parameter #1 has not been set. wherein the Parameter #1 is prompt the the domains property name in the inList criterion.

Having this problem, is this possible to solve? How?

Answer

Victor Sergienko picture Victor Sergienko · Aug 2, 2012

Take a look at GORM guide, look for "Querying associations". Let's rather try to do it all with a single query.

With new "where" query, it's

def query = DomainB.where {
  domains { someAField == 3 } && someBField == 8
}

or with CriteriaBuilder:

DomainB.withCriteria {
  domains { 
    eq 'someAField', 3 
  }
  eq 'someBField', 8
}