mongodb 多对多未加入 table
mongodb many to many without join table
原来,我指定了联系has_many服务的关系。因此,服务有一个外键 contact_id:
class Contact
include Mongoid::Document
field :name, type: String
end
class Service
field :name, type: String
field :contact_id, type: Integer
end
现在可以向服务添加额外的联系人,因此服务有很多联系人。但是,添加的联系人是已经独立存在的联系人。所以我不想将一个实体嵌入到另一个实体中。联系人和服务将始终独立存在。没有嵌入。
那么我应该只将联系人的 ID 存储在一个服务数组中吗?换句话说,我的新模型将如下所示:
class Contact
include Mongoid::Document
field :name, type: String
end
class Service
field :name, type: String
field :contact_id, type: Integer
field :contact_ids, type: Array, default: []
end
或者是否有更好的解决方案来解决这里的多对多问题(无需将一个文档嵌入另一个文档)?
对于多对多,您没有 36 个选项:您实际上有 2 个:
- 像你一样在一侧的 ID 数组
- 两边的ID数组。
"both sides" 解决方案的妙处在于,您可以从两个集合中查找查询文档以获取链接。
书籍和作者的示例:
db.books.findOne()
{
_id: 1,
title: "The Great Gatsby",
authors: [1, 5]
}
db.authors.findOne()
{
_id: 1,
firstName: "F. Scott",
lastName: "Fitzgerald",
books: [1, 3, 20]
}
原来,我指定了联系has_many服务的关系。因此,服务有一个外键 contact_id:
class Contact
include Mongoid::Document
field :name, type: String
end
class Service
field :name, type: String
field :contact_id, type: Integer
end
现在可以向服务添加额外的联系人,因此服务有很多联系人。但是,添加的联系人是已经独立存在的联系人。所以我不想将一个实体嵌入到另一个实体中。联系人和服务将始终独立存在。没有嵌入。
那么我应该只将联系人的 ID 存储在一个服务数组中吗?换句话说,我的新模型将如下所示:
class Contact
include Mongoid::Document
field :name, type: String
end
class Service
field :name, type: String
field :contact_id, type: Integer
field :contact_ids, type: Array, default: []
end
或者是否有更好的解决方案来解决这里的多对多问题(无需将一个文档嵌入另一个文档)?
对于多对多,您没有 36 个选项:您实际上有 2 个:
- 像你一样在一侧的 ID 数组
- 两边的ID数组。
"both sides" 解决方案的妙处在于,您可以从两个集合中查找查询文档以获取链接。
书籍和作者的示例:
db.books.findOne()
{
_id: 1,
title: "The Great Gatsby",
authors: [1, 5]
}
db.authors.findOne()
{
_id: 1,
firstName: "F. Scott",
lastName: "Fitzgerald",
books: [1, 3, 20]
}