Search code examples
grailsgroovygrails-orm

Grails GORM: list all with nested property


My (simplified) domain model looks like this:

class Student { 
    static hasMany = [professions:StudentProfession];
}

class StudentProfession { 
    static belongsTo = [student:Student];
    Profession profession;
}

class Profession { 
    String name;
}

What is the most efficient way to:

List all students that are taught "Programmer" and "Manager" professions

Am I forced to filter them out after querying the database?

students = students.findAll { student -> 
    student.professions.find { professionNames.contains(it.profession.name) } != null
}

Solution

  • You can do this using a GORM query:

    def studends = Student.where {
      professions {
          profession.name == "Programmer" || profession.name == "Manager"
      }
    }