Search code examples
grailsgroovygrails-orm

Searching through children of an domain object in Grails GORM


How can I write this code correctly in Groovy / Gorm?

I have a PageComponent domain class that has many Content's. I want to see if a particular PageComponent contains a Content with a specfific key.

I thought I could say:

def pageComponent = PageComponent.get(1);

if (pageComponent.contents.findByKey("textnode") {
  // update
} else {
  // insert
}

At the moment, I'm using this instead. Not very elegant...

def pageComponent = PageComponent.get(1);

def content = Content.withCriteria {
    eq "pageComponent.id", pageComponent.id
    eq "key", "textnode"
}

Solution

  • You can also use dynamic finders:

    Content.findByPageComponentAndKey(pageComponent, "textnode")