如何通过与 Mongoid 和 mongodb 的关系来实现 has_many ?

2024-01-30

使用这个修改后的例子Rails 指南 http://guides.rubyonrails.org/association_basics.html#the-has-many-through-association,如何使用 mongoid 建模关系“has_many :through”关联?

挑战在于 mongoid 不像 ActiveRecord 那样支持 has_many :through 。

# doctor checking out patient
class Physician < ActiveRecord::Base
  has_many :appointments
  has_many :patients, :through => :appointments
  has_many :meeting_notes, :through => :appointments
end

# notes taken during the appointment
class MeetingNote < ActiveRecord::Base
  has_many :appointments
  has_many :patients, :through => :appointments
  has_many :physicians, :through => :appointments
end

# the patient
class Patient < ActiveRecord::Base
  has_many :appointments
  has_many :physicians, :through => :appointments
  has_many :meeting_notes, :through => :appointments
end

# the appointment
class Appointment < ActiveRecord::Base
  belongs_to :physician
  belongs_to :patient
  belongs_to :meeting_note
  # has timestamp attribute
end

Mongoid 没有 has_many :through 或等效功能。它对于 MongoDB 来说不是那么有用,因为它不支持连接查询,因此即使您可以通过另一个集合引用相关集合,它仍然需要多个查询。

https://github.com/mongoid/mongoid/issues/544 https://github.com/mongoid/mongoid/issues/544

通常,如果 RDBMS 中存在多对多关系,您将在 MongoDB 中使用两侧包含“外”键数组的字段以不同方式对其进行建模。例如:

class Physician
  include Mongoid::Document
  has_and_belongs_to_many :patients
end

class Patient
  include Mongoid::Document
  has_and_belongs_to_many :physicians
end

换句话说,您将消除连接表,并且在访问“另一端”方面,它与 has_many :through 具有类似的效果。但在您的情况下,这可能不合适,因为您的联接表是一个约会类,它携带一些额外的信息,而不仅仅是关联。

如何建模在某种程度上取决于您需要运行的查询,但似乎您需要添加约会模型并定义与患者和医生的关联,如下所示:

class Physician
  include Mongoid::Document
  has_many :appointments
end

class Appointment
  include Mongoid::Document
  belongs_to :physician
  belongs_to :patient
end

class Patient
  include Mongoid::Document
  has_many :appointments
end

对于 MongoDB 中的关系,您始终必须在嵌入文档或关联文档之间做出选择。在您的模型中,我猜测 MeetingNotes 是嵌入关系的良好候选者。

class Appointment
  include Mongoid::Document
  embeds_many :meeting_notes
end

class MeetingNote
  include Mongoid::Document
  embedded_in :appointment
end

这意味着您可以将注释与约会一起检索,而如果这是关联,则需要多个查询。您只需记住单个文档的 16MB 大小限制,如果您有大量会议记录,该限制可能会发挥作用。

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

如何通过与 Mongoid 和 mongodb 的关系来实现 has_many ? 的相关文章

随机推荐