查询空 has_many 通过

Query for empty has_many through

如何查询 has_many :through 以查看哪些记录在另一侧具有空关联? (我正在使用 rails 5)

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 }
Specialty.includes(:doctor_profiles).where(doctor_profiles: { id: nil })

有关 AR 查询的更多信息,请参阅 Active Record Query Interface

因为你在 Rails >= 5,你可以使用 left_outer_joins (thx @gmcnaughton):

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

您也可以使用以下查询来实现。

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

以上语句将在查询中创建一个查询。不需要 table 加入。