Search code examples
grailsgrails-ormcriteria

GORM Criteria Query: Finding Children with specific properties


Have the following Domain modal:

class TransactionHeader {
  static hasMany = [details: TransactionDetail]
}

class TransactionDetail {
   static belongsTo = [header: TransactionHeader]
   Product product
}

I'm trying to write a criteria query that will return all the TransactionHeader rows that contain TransactionDetails with 2 different Products. This is what I have so far and it isn't doing exactly what I'm after:

def list = TransactionHeader.withCriteria {
    details {
      and {
        eq("product", product1)
        eq("product", product2)
      }
    }
}

What's happening is it is return rows that contain at least 1 detail with 1 of the products. I need rows that have 2 details, each with one of the products.


Solution

  • Feels like you want to move details out of that, so actually

    def list = TransactionHeader.withCriteria {
        and {
           details {
              eq("product", product1)
           }
           details {
              eq("product", product2)
           }
        }
    }
    

    Not sure how hibernate / gorm will deal this, though.