MongoMapper:如何创建这样的模型
假设我们有两个模型:任务和用户。 因此,一个用户可以有很多任务,任务也应该可以有很多用户。但是,任务还应该有一个唯一的创建者,同时也是用户。
示例:
此上下文中的任务如下所示: 任务 ID、任务创建者、应该执行该任务的用户
User_1 创建了一个任务,然后他就是创建者。 User_1 将 User_2 和 User_3 指定为应执行该任务的用户。所以最后这两个用户不是任务的创建者。
如何创建此模型,以便如果我有一个任务对象,我可以找到它的创建者和应该完成它的用户。如果我有一个用户,我该怎么做才能找到他创建的所有任务以及他应该完成的所有任务。
Suppose we have two models, Task and User.
So a user can have many tasks and tasks should be able to have many users too. But, a task should also have a unique creator who is also a user.
Exemple:
A task in this context is like this:
Task ID, Task Creator, Users who should do the task
User_1 creates a task and he is then the creator.
User_1 specifies User_2 and User_3 as users who should do the task. So these two last users are not creators of task.
How do I create this models so that if I have a task object, I can find it's creator and users who should complete it. And how do I do, if I have a user, to find all tasks he created and all tasks he should complete.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您需要任务和用户之间存在多对多关系,并且用户和任务之间需要额外的一对多关系,指向创建者(用户)。
沿着这些思路:(我通常使用 Mongoid,因此请仔细检查 MongoMapper API 中关系的语法 - 下面的链接..您可以手动指定 :foreign_key 和 :class)
这个想法是,您在模型,一种对多对多关系进行建模的模型
通过它您可以获取
signed_users
或signed_tasks
,以及一对多关系,通过它您可以获取creator
任务,或给定用户的created_tasks
。如果您为关系选择这些名称,那么哪个是哪个就会很清楚。请参阅:
http://mongomapper.com/documentation/plugins/associations.html
You'll need a many-to-many relationship between the Tasks and Users, and you need an additional one-to-many relationship between Users and Tasks, pointing to the creator (User).
Something along these lines: (I usually use Mongoid, so double-check the syntax for the relations in the MongoMapper API - link below.. you might to manually specify :foreign_key and :class)
The idea is that you have two relationships between the models, one which models the many-to-many relationship
with which you get either to the
assigned_users
orassigned_tasks
, and a one-to-many relationship with which you get to either thecreator
of a task, or thecreated_tasks
for a given user. If you chose these names for the relationships, it will be clear which is which.See:
http://mongomapper.com/documentation/plugins/associations.html
Tilo 建议的关于如何对数据建模的答案是正确的,但示例代码不正确并且无法工作。
:as
选项用于多态关联,您想要使用:foreign_key
选项。此外,不能有两个名称相同的关联。请参阅下面的修改后的代码。另请参阅:
The answer suggested by Tilo is correct about how to model the data, but the example code is incorrect and will not work. The
:as
option is for polymorphic associations, you want to use the:foreign_key
option. Also, you can't have two associations named the same. See below for revised code.See also: