2016-10-11 112 views
1

如何查詢has_many :through以查看哪些記錄在另一端具有空關聯? (我使用的軌道5)查詢空has_many通過

class Specialty 
    has_many :doctor_specialties 
    has_many :doctor_profiles, through: :doctor_specialties 

class DoctorProfile 
    has_many :doctor_specialties 
    has_many :specialties, through: :doctor_specialties 

class DoctorSpecialty 
    belongs_to :doctor_profile 
    belongs_to :specialty 

我可以列舉在Specialty做到這一點,但我希望做一個SQL查詢。

Specialty.includes(:doctor_profiles).all.select{|x| x.doctor_profiles.length == 0 } 

回答

3
Specialty.includes(:doctor_profiles).where(doctor_profiles: { id: nil }) 

對AR查詢更多信息,請參見Active Record Query Interface

既然你是on Rails的> = 5,你可以使用left_outer_joins(THX @gmcnaughton):

Specialty.left_outer_joins(:doctor_profiles).where(doctor_profiles: { id: nil }) 
+1

從Rails 5開始,您可以使用'left_outer_joins'而不是'includes' - 請參閱http://guides.rubyonrails.org/active_record_querying.html#left-outer-joins – gmcnaughton

0
Speciality.joins('left join doctor_profiles on doctor_profiles.speciality_id = specialities.id').where(doctor_profiles: {id: nil}) 
1

您也可以做到這一點使用下面的查詢。

Specialty.where.not(id: DoctorSpecialty.select(:speciality_id)) 

上面的語句會在查詢中創建一個查詢。不需要表連接。