我有三个模型,有很多关联:
class School < ApplicationRecord
has_many :school_teacher_subjects
has_many :teachers, through: :school_teacher_subjects
has_many :subjects, through: :school_teacher_subjects
end
class Teacher < ApplicationRecord
has_many :school_teacher_subjects
has_many :schools, through: :school_teacher_subjects
has_many :subjects, through: :school_teacher_subjects
end
class Subject < ApplicationRecord
has_many :school_teacher_subjects
has_many :teachers, through: :school_teacher_subjects
has_many :schools, through: :school_teacher_subjects
end
class SchoolTeacherSubject < ApplicationRecord
belongs_to :teacher
belongs_to :school
belongs_to :subject
end
我需要知道一个学校有多少老师,在一个优化的查询中,但我不知道我该怎么做
这是school_teacher_subjects表:
+----+------------+-----------+------------+
| id | teacher_id | school_id | subject_id |
+----+------------+-----------+------------+
| 1 | 1 | 1 | 1 |
| 2 | 2 | 1 | 1 |
| 3 | 2 | 1 | 2 |
| 4 | 3 | 2 | 1 |
| 5 | 3 | 2 | 2 |
+----+------------+-----------+------------+
我需要这样的东西:
+-------------+-------------+---------------+
| School name | school city | Teacher count |
+-------------+-------------+---------------+
| School A | New York | 2 |
| School B | Orlando | 1 |
+-------------+-------------+---------------+
姓名和城市数据存储在学校表
中有人帮助我吗?
答案 0 :(得分:1)
有几种方法:
1)使用 rails查询,您需要将组与选择 + 计数结合使用,将它们合并为一个查询:
要获得只有教师的学校,请使用加入
School.joins(:school_teacher_subjects => [:teacher]).select("schools.id, schools.name, schools.city, count(DISTINCT teachers.id) as teacher_count ").group("schools.id")
要让所有有或没有老师的学校,请使用 left_outer_joins :
School.left_outer_joins(:school_teacher_subjects => [:teacher]).select("schools.id, schools.name, schools.city, count(DISTINCT teachers.id) as teacher_count ").group("schools.id")
2)另一种方法是通过在学校类中附加as_json
来获取数据时依赖学校模型,如下所示(如果你没有大量获取):
def as_json(options = {})
if options[:index]
{
id: id,
school_name: name,
city_name: city_name, # in case you have the city name in school class
teachers: teachers.count
}
else
super
end
end
然后按如下方式调用模型:
Teacher.as_json(index: true)