Grails find domain objects with many to many relationship, with a list as parameter

767 Views Asked by At

I have a simple class Song, to which I can attribute some tags :

class Song {
    String title
    static hasMany = [tags:Tag]
}

Then, i would like to be able to find all songs having a given list of tags, for example this would look like :

List<Song> results = Song.findAll("where tags contains ?", [myTagList]);

For example, if I have :

a Song S1 with tags T1
a Song S2 with tags T1 T2 T3
a Song S3 with tags T1 T3
a Song S4 with tags T1 T2 T3 T4

And I execute my query with myTagList containing T1, T2, T3, then the call will return S2 and S4.

Is there any efficient way to perform this ?

2

There are 2 best solutions below

1
On

What about a dynamic finder?

List<Song> results = Song.findAllByTagsInList(myTagList);
5
On

It should be possible to use criteria with an "in" query:

Song.createCriteria().list{
    "in"("tags",myTagList)
}