2017-06-29 141 views
2

我有模型,醫師,has_many患者。嘗試寫一個查詢,只會導致醫生擁有所有治癒的患者。因此,每位醫師患者必須具有「is_cured:true」的屬性(或者對於所有內科醫生患者至少不是零)。Ruby has_many與Postgres數據庫相關的模型查詢(Rails 5)

有這到目前爲止,但醫生們表示只是有一個治癒病人,不是所有的時候了:

@physicians = Physician.includes(:patients) .where.not(patients: { id: nil }) .where(patients: { is_cured: true })

型號:

class Physician < ApplicationRecord 
    has_many :patients 
    has_many :recommendations, through: :patients 
end 

class Patient < ApplicationRecord 
    belongs_to :physician 
    belongs_to :recommendation 
end 

class Recommendation < ApplicationRecord 
    has_many :patients 
    has_many :physicians, through: :patients 
end 

感謝您能給任何幫助!

回答

0
# Fetches physicians who have at-least one uncured patient 
phys_with_uncured_patients = Physician.joins(:patients).where(patients: { is_cured: false }) 

#Fetches physicians who have at-least one patient and all are cured. 
Physician.joins(:patients).where.not(id: phys_with_uncured_patients) 
0
physician_ids = Patient.where(is_cured: false).pluck(:physician_id) 

Physician.joins(:patients).where.not(id: physician_ids) 
+0

問題也有望篩選出誰擁有零名病人的醫生,你的第二個查詢不過濾。 – Ucpuzz

+0

在這種情況下'加入'將做到這一點。好點子。 –