【问题标题】:Query for empty has_many through通过查询空的has_many
【发布时间】:2016-10-11 14:57:20
【问题描述】:

如何查询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 }

【问题讨论】:

    标签: ruby-on-rails activerecord ruby-on-rails-5


    【解决方案1】:
    Specialty.includes(:doctor_profiles).where(doctor_profiles: { id: nil })
    

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

    由于您在 Rails >= 5 上,您可以使用 left_outer_joins(谢谢 @gmcnaughton):

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

    【讨论】:

    【解决方案2】:

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

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

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

    【讨论】:

      【解决方案3】:
      Speciality.joins('left join doctor_profiles on doctor_profiles.speciality_id = specialities.id').where(doctor_profiles: {id: nil})
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多