Rails:根据直通表属性进行 Has_many 直通查询

2024-01-11

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

使用此处的示例:http://guides.rubyonrails.org/association_basics.html#the-has_many-through-association 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

约会表有一列名为约会日期

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


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)

Edit:

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

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Rails:根据直通表属性进行 Has_many 直通查询 的相关文章

随机推荐