Search code examples
grailsgrails-orm

Grails "deep" criteria + one-to-many relation


I have the following table structures:

Task - (has one) - mandate
Mandate - (has many) - mandateContacts (of type Contact)
Contact

Of course, Hibernate created a table called mandate_contact which links those contacts to a mandate.

I have to write a criteria starting from the Task table which should sound like:

Fetch a task if one of the contacts associated to a mandate has a specific name.

So far, I have created aliases like:

createAlias('mandate', 'mnd', CriteriaSpecification.LEFT_JOIN)

Solution

  • This is quite simple using the criteria builder:

    def results = Task.createCiteria().list() {
      mandate {
        mandateContacts {
          eq('name', 'whatever value you want to match')
        }
      }
    }
    

    The above assumes that your Task domain class which has a mandate property of the Mandate domain class type. The Mandate has a collection called mandateContacts which is a collection of the Contact domain class and that the Contact domain class has a property called name which you want to match against.

    I recommend you read the documentation I linked to to understand createCriteria and how it functions.