use*_*587 2 activerecord ruby-on-rails ruby-on-rails-5
如何查询 ahas_many :through以查看哪些记录在另一侧具有空关联?(我正在使用导轨 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
Run Code Online (Sandbox Code Playgroud)
我可以通过枚举来做到这一点,Specialty但我想在 SQL 查询中做到这一点。
Specialty.includes(:doctor_profiles).all.select{|x| x.doctor_profiles.length == 0 }
Run Code Online (Sandbox Code Playgroud)
Specialty.includes(:doctor_profiles).where(doctor_profiles: { id: nil })
Run Code Online (Sandbox Code Playgroud)
有关AR 查询的更多信息,请参阅Active Record 查询接口。
由于您在 Rails >= 5 上,您可以使用left_outer_joins(thx @gmcnaughton ):
Specialty.left_outer_joins(:doctor_profiles).where(doctor_profiles: { id: nil })
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
332 次 |
| 最近记录: |