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 大小限制,如果您有大量会议记录,该限制可能会发挥作用。