RoR中模型的特定关联数

时间:2015-06-19 10:17:27

标签: sql ruby-on-rails postgresql

所以我有一个模型Doctor,每个医生都有很多appointments,每个约会轮流都有date(作为日期时间列)。

我需要显示一份清单,比如30名医生,每位医生,我需要显示他或她在6月1日的任命数量,所以我想知道我该怎么办?

我能提出的最佳选择是使用嵌套式SQL:

SELECT doctors.*, (SELECT COUNT(*) from appointments a WHERE a.date = 01.06.2014 AND a.doctor_id = doctors.id) as appointments_number FROM doctors;

(我知道日期没有正确填写但是我太懒了以正确的方式谷歌,这没关系)

那么,有没有更简单的方法呢?

2 个答案:

答案 0 :(得分:2)

按要选择的doctors表的所有列进行分组并添加计数

SELECT d.id, d.name, count(a.id) as appointments
from FROM doctors d
join appointments a on a.doctor_id = d.id
WHERE a.date = '2014-06-01'
group by d.id, d.name

答案 1 :(得分:0)

更好的解决方案是使用约会模型中的范围:

class Appointment < ActiveRecord::Base
  scope :for_date, -> (date) { where(date: date) }
end

Doctor.includes(:appointments).merge(Appointment.for_date()).count