使用 the Rails guides 中的这个修改示例,如何使用 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
通常,如果您在 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 具有类似的效果。但在您的情况下,这可能不合适,因为您的联接表是一个 Appointment 类,其中包含一些额外信息,而不仅仅是关联。
如何对此建模在某种程度上取决于您需要运行的查询,但您似乎需要添加 Appointment 模型并定义与 Patient 和 Physician 的关联,如下所示:
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 大小限制,如果您有大量 session 记录,这可能会发挥作用。
关于ruby-on-rails - 如何实现has_many :through relationships with Mongoid and mongodb?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7000605/
相关文章:
mongodb - 如何从 Mac OS 终端连接到远程 mongo 服务器
javascript - 如何跨 NodeJs 应用程序和模块正确重用与 Mongodb 的连接
windows - MongoDB 新手无法运行命令 mongo
javascript - 在 Mongoose 中引用另一个模式
mongodb - 如何查看 mongodb 从 mongo shell 监听的端口?
mongodb - 什么是 Mongoose 错误 Cast to ObjectId failed
mongodb - 与关系数据库相比,使用像 MongoDB 这样的无模式数据库有什么优势?