Search code examples
sqlgrailsgrails-orm

Grails: HasMany Intersection Query


Given the following domain structure:

Book {
    static hasMany = [tags: Tag]
}

Tag {
    String name
}

I'm trying to find a way that given a Book I can find any other books containing any of this book's tags.

I've tried:

Book.findAllByTagsInList(myBook.tags)

But as expected the 'List in List' query isn't producing the required results.


Solution

  • You can use Criteria as

    def books = Book.createCriteria().listDistinct{
        tags{
            'in'('id', myBook.tags*.id)
        }
    }
    

    or use HQL as

    def books = Book.executeQuery("select distinct b from Book as b \
                                   inner join b.tags as tag \
                                   where tag.id in (:tags)", 
                                   [tags: myBook.tags*.id])