Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Grails: How to query objects in many to many mapping?

Hello I have the follwing domain classes.

class Student {
   int age
   static hasMany = [courses:Course]
}

class Course {
   String name
   static hasMany = [students:Student]
}

I want to find the Students taking Course (with id 1), with age 7.

Could I do that with dynamic finder or criteria builder or HQL?

I do not want to do following as it load all students so inefficient:

def course = Course.get(1);
course.students.findAll{ it.age == 7 }
like image 972
enesness Avatar asked Jun 11 '11 15:06

enesness


1 Answers

def studs = Student.withCriteria {
  eq('age', 7)
  courses {
    eq('id', 1)
  }
}

It's in GORM doc, section "Criteria/Querying Associations".

like image 163
Victor Sergienko Avatar answered Oct 08 '22 21:10

Victor Sergienko