Enrico Susatyo
Enrico Susatyo

Reputation: 19800

Querying a list of items from a one-to-many relationship in Grails

If I have a class called Artist, which has many Song:

class Artist {
    String name
    static hasMany = [songs : Song]
}

class Song {
    String title
    Integer duration
}

I want to know which artists sang a list of titles. For example I want to know the artists who sang Hello, My Love, and Yesterday (An array of String). What is the best way to do this?

I tried using criteria and findAll, but can't really figure out which is the best way. Any ideas?

Upvotes: 1

Views: 365

Answers (1)

Burt Beckwith
Burt Beckwith

Reputation: 75681

This HQL will work:

def artists = Artist.executeQuery(
   'select distinct a from Artist a join a.songs song where song.title in (:titles)',
   [titles: ['Hello', 'My Love', 'Yesterday']])

It will return a list of artists, but if there's only one result you can get it as artists[0]

Upvotes: 3

Related Questions