user1080894
user1080894

Reputation:

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.

Upvotes: 1

Views: 466

Answers (1)

dmahapatro
dmahapatro

Reputation: 50285

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])

Upvotes: 1

Related Questions