gpt4 book ai didi

ruby-on-rails - Ruby has_many 关联模型查询与 Postgres 数据库 (Rails 5)

转载 作者:太空宇宙 更新时间:2023-11-03 16:42:08 26 4
gpt4 key购买 nike

我有模型,医师,有_很多患者。尝试编写一个查询,该查询只会导致 Physicians that have all cured patients。因此,医生的每个患者都必须具有属性“is_cured: true”(或者至少对于所有医生患者而言不是 nil)。

到目前为止,医生只是在治愈一名患者而非所有患者时出现:

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

模型:

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

感谢您提供的任何帮助!

最佳答案

# 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)

关于ruby-on-rails - Ruby has_many 关联模型查询与 Postgres 数据库 (Rails 5),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44834073/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com