2016-10-11 110 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)) 

上面的语句会在查询中创建一个查询。不需要表连接。