1

我试图描述与包含额外信息字段的链接表的 1:NM:1 关系。table1 和 table3 都有很多字段。

现有表如下所示:

Table1      1:N   Table2       M:1   Table3
somethings        extra info         otherthings
id                table1_id          id
                  table3_id

table2.extra 信息让我搞砸了。我如何用 mongoid 来描述这个?

class Model1
  include Mongoid::Document
  field :somethings, :type => String
  has_many_and_belongs_to :inbetween
end

class ModelInbetween
  include Mongoid::Document
  field :extra_info, :type => String

  ???
end

class Model2
  include Mongoid::Document
  field :otherthings, :type => String

  has_many_and_belongs_to :inbetween
end
4

1 回答 1

1

在 Mongoid 中,has_manybelongs_to用于表示1:N两个集合之间的关系。has_many_and_belongs_to仅用于N:N关系。有关官方文档,请参见此处。据我所知,您的表格应如下所示:

class Model1
  include Mongoid::Document
  field :somethings, :type => String
  has_many :modelInbetweens
end

class ModelInbetween
  include Mongoid::Document
  field :extra_info, :type => String

  belongs_to :model1
  belongs_to :model2

end

class Model2
  include Mongoid::Document
  field :otherthings, :type => String

  has_many :modelinbetweens
end

另外,请务必注意在定义关系时是否应使用模型的复数/单数形式。

于 2013-07-17T06:28:20.303 回答