【问题标题】:Grails: How to query objects in many to many mapping?Grails:如何在多对多映射中查询对象?
【发布时间】:2011-09-13 02:11:29
【问题描述】:

您好,我有以下域类。

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

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

我想找到年龄为 7 岁的正在学习课程的学生(id 为 1)。

我可以使用动态查找器或标准生成器或 HQL 来做到这一点吗?

我不想做以下事情,因为它让所有学生都如此低效:

def course = Course.get(1);
course.students.findAll{ it.age == 7 }

【问题讨论】:

    标签: grails grails-orm grails-domain-class


    【解决方案1】:
    def studs = Student.withCriteria {
      eq('age', 7)
      courses {
        eq('id', 1)
      }
    }
    

    位于GORM doc,“条件/查询关联”部分。

    【讨论】:

    • 谢谢,这就是我要找的
    【解决方案2】:

    您可以使用动态查找器:

    def students = Student.findByCourseAndAge(Course.load(1), 7)
    

    通过使用load() 而不是get(),您可以避免检索整个 Course 实例而只需引用其 ID。

    另一种选择是 HQL:

    def students = Student.executeQuery(
       'from Student s where s.course.id = :courseId and s.age = :age',
       [courseId: 1, age: 7])
    

    【讨论】:

    • 你好,伯特。学生没有“课程”字段,它有“课程”。我不能做 findByCourse,我可以做 findByCourses,但我可以比较集合。
    猜你喜欢
    • 2018-09-18
    • 2012-02-21
    • 2020-12-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多