[英]Number of specific associations for model in RoR
因此,我有一個示范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;
(我知道日期未正確填寫,但是我懶得用正確的方式搜索Google,這沒關系)
那么,有沒有更簡單的方法呢?
按您要選擇的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
更好的解決方案是使用約會模型中的范圍:
class Appointment < ActiveRecord::Base
scope :for_date, -> (date) { where(date: date) }
end
Doctor.includes(:appointments).merge(Appointment.for_date()).count
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.