引用许多自身的模型?

发布于 2024-12-07 19:28:30 字数 183 浏览 1 评论 0原文

给定以下类,我如何允许节点与其他节点(例如 parent_nodechild_nodes)具有多对多关系?

class Node
  include MongoMapper::Document

  key :text, String
end

Given the following class, how would I allow a node to have a many to many relationship with other nodes (such as parent_node and child_nodes)?

class Node
  include MongoMapper::Document

  key :text, String
end

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

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

发布评论

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

评论(1

記憶穿過時間隧道 2024-12-14 19:28:30

孩子可以有多个父母吗?如果没有,many/belongs_to 应该可以正常工作:

class Node
  include MongoMapper::Document

  key :text, String
  key :parent_node_id, ObjectId

  belongs_to :parent_node, :class_name => 'Node'
  many :child_nodes, :foreign_key => :parent_node_id, :class_name => 'Node'
end

如果节点可以有多个父节点......

class Node
  include MongoMapper::Document

  key :text, String
  key :parent_node_ids, Array, :typecast => 'ObjectId'

  many :parent_nodes, :in => :parent_node_ids, :class_name => 'Node'

  # inverse of many :in is still forthcoming in MM
  def child_nodes
    Node.where(:parent_node_ids => self.id)
  end
end

# ... or store an array of child_node_ids instead ...

class Node
  include MongoMapper::Document

  key :text, String
  key :child_node_ids, Array, :typecast => 'ObjectId'

  many :child_nodes, :in => :child_node_ids, :class_name => 'Node'

  # inverse of many :in is still forthcoming in MM
  def parent_nodes
    Node.where(:child_node_ids => self.id)
  end
end

这就是您正在寻找的吗?

Can children have more than one parent? If not, many/belongs_to should work fine:

class Node
  include MongoMapper::Document

  key :text, String
  key :parent_node_id, ObjectId

  belongs_to :parent_node, :class_name => 'Node'
  many :child_nodes, :foreign_key => :parent_node_id, :class_name => 'Node'
end

If nodes can have multiple parents...

class Node
  include MongoMapper::Document

  key :text, String
  key :parent_node_ids, Array, :typecast => 'ObjectId'

  many :parent_nodes, :in => :parent_node_ids, :class_name => 'Node'

  # inverse of many :in is still forthcoming in MM
  def child_nodes
    Node.where(:parent_node_ids => self.id)
  end
end

# ... or store an array of child_node_ids instead ...

class Node
  include MongoMapper::Document

  key :text, String
  key :child_node_ids, Array, :typecast => 'ObjectId'

  many :child_nodes, :in => :child_node_ids, :class_name => 'Node'

  # inverse of many :in is still forthcoming in MM
  def parent_nodes
    Node.where(:child_node_ids => self.id)
  end
end

Is that what you're looking for?

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