首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用Postgres数据库(Rails5)查询Ruby has_many关联模型

使用Postgres数据库(Rails5)查询Ruby has_many关联模型
EN

Stack Overflow用户
提问于 2017-06-30 04:06:26
回答 2查看 186关注 0票数 2

我有模型,内科医生,has_many病人。尝试编写一个查询,使其只得到所有已治愈患者的医生。因此,对于内科医生来说,每个患者必须具有"is_cured: true“属性(或者至少对于所有内科医生患者来说不是空的)。

到目前为止已经有了这个,但医生们只有一个治愈的病人,而不是所有的:

@physicians = Physician.includes(:patients) .where.not(patients: { id: nil }) .where(patients: { is_cured: true })

型号:

代码语言:javascript
复制
class Physician < ApplicationRecord
  has_many :patients
  has_many :recommendations, through: :patients
end

class Patient < ApplicationRecord
  belongs_to :physician
  belongs_to :recommendation
end

class Recommendation < ApplicationRecord
  has_many :patients
  has_many :physicians, through: :patients
end

感谢您所能提供的任何帮助!

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2017-06-30 04:48:03

代码语言:javascript
复制
# Fetches physicians who have at-least one uncured patient
phys_with_uncured_patients = Physician.joins(:patients).where(patients: { is_cured: false })

#Fetches physicians who have at-least one patient and all are cured.
Physician.joins(:patients).where.not(id: phys_with_uncured_patients)
票数 0
EN

Stack Overflow用户

发布于 2017-06-30 05:31:31

代码语言:javascript
复制
physician_ids = Patient.where(is_cured: false).pluck(:physician_id)

Physician.joins(:patients).where.not(id: physician_ids)
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/44834073

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档