gpt4 book ai didi

ruby-on-rails - rails : Has_many through query depending on the through table attribute

转载 作者:行者123 更新时间:2023-12-04 01:51:51 26 4
gpt4 key购买 nike

has_many 通过查询遇到一些问题。

使用此处的示例:http://guides.rubyonrails.org/association_basics.html#the-has_many-through-association

class Physician < ActiveRecord::Base
has_many :appointments
has_many :patients, :through => :appointments
end

class Appointment < ActiveRecord::Base
belongs_to :physician
belongs_to :patient
end

class Patient < ActiveRecord::Base
has_many :appointments
has_many :physicians, :through => :appointments
end

Appointment 表有一列名为 约会日期

我如何从特定医生那里获得在给定日期预约的所有患者?

最佳答案

Patient.includes(:physicians, :appointments).where('physicians.id = ? AND appointments.appointment_date = ?', <id or ids array>, Date.today)

其中 Date.today 可以用任何东西更改,并且医生由一个 id 或一组 id 指定。

你也可以这样做:
physician = Physician.find(id)
patients = physician.patients.includes(:appointments).where('appointments.appointment_date = ?', some_date)

编辑:

在 Rails 4 及更高版本中,您需要添加 references(:appointments)到查询以在 where 子句中使用约会。

关于ruby-on-rails - rails : Has_many through query depending on the through table attribute,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15641504/

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