Search code examples
grailshqlgrails-orm

Grails GORM Querying the many side of an association using HQL


I have a one to many relationship between a Course and Categories

class Course {

    String code     

    static hasMany = [categories:CourseCategory]
}


Class CourseCategory {

    String name
}

I need to query courses based on a list of categories. I have tried the query

courseInstanceList = Course.findAll("from Course c inner join c.categories cts where cts.id in :categoryIds",[categoryIds:categoryIds])

But this query returns both Courses and CourseCategories - just wondering how to create a query to just return courses?


Solution

  • You can use the createCriteria method:

    def c = Course.createCriteria()
    println (c.listDistinct {
        categories {
            'in' 'id', [1L, 2L, 3L]
        }
    })