Search code examples
grailsassociationsnamed-query

Grails named query - find by association


I want to create a named query that will find all objects of one class, based on a property (or properties) of child class properties.

I want to be able to find all Bars where Foo.me == "some string"

So, I have this, and it doesn't work:

class Foo {
    String me
}

class Bar {
    Foo foo

    static namedQueries = {
        findByFooMe { meStr ->
            eq(foo.me, meStr)
        }
    }
}

What does the correct syntax look like please? Also, how does it change if Bar hasMany Foos, and I want to find all Bars where one of its Foo,me properties is "search string"?

i.e.

class Bar {
    static hasMany [foos: Foo]
} 

Solution

  • While I wouldn't recommend using findBy as the prefix to a named query, you are close to having the right implementation. Here is an updated version with a new name for the query too.

    static namedQueries = {
        locateByFooMe { meStr ->
            foo {
              eq('me', meStr)
            }
        }
    }
    

    If you change your relationship to a collection (One to Many) just make sure the property name foo (in this case) changes to whatever you change it to (foos in your question) and the above query will still continue to work.