MongoDB/Mongoid多对多建模问题
所以我在 Mongo/Mongoid 中建模时遇到了一个问题:
团队可以参加一个活动,每个活动都会有每个团队的结果(得分、导致得分的动作等) 基本上我想显示该事件的某种记分牌。
这就是我所拥有的:
Event
has_and_belongs_to_many :teams
Team
field :name
field :color
has_and_belongs_to_many :events
这很好,但我需要知道如何对每个团队和活动之间的关系进行建模。
TeamEventStats (probably not the best name)
field :score, :type => Integer
# etc. etc.
在 ActiveRecord/RDBMS 中,我可以做一个直通(连接)模型并继续我的快乐之路,但是 我不知道如何在 Mongo 中执行此操作。 有人知道这样做的好方法或建立关系模型的更好方法吗?
So I'm having a problem modeling this in Mongo/Mongoid:
Teams can participate in an event and each event will have results for each team (score, actions leading the the score, etc.)
Basically I want to display a scoreboard of sorts for the event.
So here is what I have:
Event
has_and_belongs_to_many :teams
Team
field :name
field :color
has_and_belongs_to_many :events
This works fine but I need to know how to model the relationship between each team and the event.
TeamEventStats (probably not the best name)
field :score, :type => Integer
# etc. etc.
In ActiveRecord/RDBMS I could do a through (join) model and go on my merry way but
I don't know how to do this in Mongo.
Anyone know a good way of doing this or a better way of modeling the relationship?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这可能会帮助你。 http://mongoid.org/docs/relations/referenced/nn.html
this may help u out. http://mongoid.org/docs/relations/referenced/n-n.html
A has many through 实际上只是通过几个多对一来创建多对多,还有一个额外的好处是,除了外键之外,您还可以存储关系数据(例如您的团队统计数据)。因此,您可以使用以下内容轻松地在 Mongoid 中完成此操作:
不过,这没有任何层次结构。如果您需要能够查询两者(给我事件 A 的所有团队的统计数据,也给我 #1 团队的所有事件的统计数据),那么它主要是一个关系模式。知道我的意思吗?因此,除非应用程序中有很多其他基于分层/文档的数据,否则我可能会选择 RDBMS。
但是,如果您只需要按事件查询统计信息,那么您可以通过在每个事件中嵌入团队统计信息而不是通过另一个集合关联事件和团队来使文档更加友好。
按照相同的逻辑,如果您只需要查询团队的统计数据,那么您可以将事件统计数据嵌入到每个团队中。
A has many through is really just a couple many-to-one's to create a many-to-many, with the added bonus that you can store relationship data in addition to the foreign keys (like your team stats). So you can easily accomplish this in Mongoid using something like:
There's nothing hierarchical about this though. If you need to be able to query both (give me the stats for all team for Event A, also give me the stats for all events for Team #1) then it's primarily a relational schema. Know what I mean? So unless you have a lot of other hierarchical / document based data in the app, I'd probably go with an RDBMS.
However, if you only ever needed to query stats by the event then you could make this more document friendly by embedding team stats within each event instead of associating Events and Team via another collection.
By the same logic, if you only ever needed to query stats by the team then you could embed event stats within each team.