使用 MongoMapper 进行 MongoDB 设计中的多对多与一对多

发布于 2024-12-28 04:35:44 字数 679 浏览 2 评论 0原文

有一个这样的例子:

class Book
  include MongoMapper::Document
  key :title
  key :author_ids, Array
  many :authors, :in => :author_ids
end

class Author
  include MongoMapper::Document
  key :name
end

它相当于

class Book
  include MongoMapper::Document
  key :title
  many :AuthorHasBook
end

class AuthorHasBook
  include MongoMapper::Document
  key :written_time

  belongs_to :book, :class_name => "Book"
  belongs_to :author, :class_name => "Author"
end

class Author
  include MongoMapper::Document
  key :name
  many :AuthorHasBook
end

Which is better吗?我想如果我需要为“关系”实体添加一些字段,我必须使用第二个解决方案?

提前致谢!

There is one example like this:

class Book
  include MongoMapper::Document
  key :title
  key :author_ids, Array
  many :authors, :in => :author_ids
end

class Author
  include MongoMapper::Document
  key :name
end

Is it equivalent to

class Book
  include MongoMapper::Document
  key :title
  many :AuthorHasBook
end

class AuthorHasBook
  include MongoMapper::Document
  key :written_time

  belongs_to :book, :class_name => "Book"
  belongs_to :author, :class_name => "Author"
end

class Author
  include MongoMapper::Document
  key :name
  many :AuthorHasBook
end

Which is better? I guess if I need to add some fields for the "relational" entity, I have to use the 2nd solution?

Thanks in advance!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

捂风挽笑 2025-01-04 04:35:44

您必须使用

many :author_has_books

MongoMapper 才能获取您的类名并将其关联起来。不确定它是否会以其他方式工作。

唯一的区别是您可以反转多对多关联。

You would have to use

many :author_has_books

so MongoMapper can pick up your class name and associate it. Not sure it will work otherwise.

The only other difference is that you can have reverse many to many associations.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文