gpt4 book ai didi

ruby - Mongoid:如何实现嵌入式文档之间的关系?

转载 作者:数据小太阳 更新时间:2023-10-29 06:58:29 26 4
gpt4 key购买 nike

我有一个情况,我有一个父文档,我想要两种不同类型的嵌入文档:一个作为父文档,另一个作为子文档,带有可选的父文档。例如:

class ParentDoc
include Mongoid::Document
embeds_many :special_docs
embeds_many :special_doc_groupings
end

class SpecialDoc
include Mongoid::Document
embedded_in :parent_doc
belongs_to :special_doc_groupings
end

class SpecialDocGrouping
include Mongoid::Document
embedded_in :parent_doc
has_many :special_docs
end

在此示例中,SpecialDocs 和 SpecialDocGroupings 可以不存在任何关系,也可以选择具有父子关系。

但是,这是一个无效的 Mongoid 关联,因为我们得到这个错误:

Mongoid::Errors::MixedRelations:

Problem: Referencing a(n) SpecialDoc document from the SpecialDocGrouping document via a relational association is not allowed since the SpecialDoc is embedded.

Summary: In order to properly access a(n) SpecialDoc from SpecialDocGrouping the reference would need to go through the root document of SpecialDoc. In a simple case this would require Mongoid to store an extra foreign key for the root, in more complex cases where SpecialDoc is multiple levels deep a key would need to be stored for each parent up the hierarchy.

Resolution: Consider not embedding SpecialDoc, or do the key storage and access in a custom manner in the application code.

除了 Mongoid 不支持这一事实之外,我没有发现我尝试创建的关联类型有任何问题。

我如何自己实现这种类型的关联?

最佳答案

关联无效,因为当您引用嵌入式模型时,Mongoid 不会将父键存储为外键。这意味着如果您有:

Class Parent        
embeds_many :children
end

Class Child
embedded_in :parent
end

您不能引用仅存储其外键的子文档,但您需要存储所有父键,直到到达根。在这种情况下,根由第一个父代表示,您需要存储 2 个键。

您可以手动完成此操作,并毫无问题地创建这种类型的关联。

您的情况有点不同(并且更容易),因为您想要在嵌入同一父项的两个模型之间创建关联。这意味着理论上您不需要存储父 key ,因为模型共享相同的根。Mongoid 不处理这种情况,因此您需要手动创建关联规则和方法。

Class Bar
embeds_many :beers
embeds_many :glasses
end

Class Beer
embedded_in :bar
# Manual has_many :glasses association
def parent
self.bar
end

def glasses
parent.glasses.where(:beer_id => self.id)
end

end

Class Glass
embedded_in :bar
# Manual belongs_to :beer association
field :beer_id, type: Moped::BSON::ObjectId
def parent
self.bar
end

def beer
parent.beers.find(self.beer_id)
end
end

(代码未测试)

关于ruby - Mongoid:如何实现嵌入式文档之间的关系?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16203108/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com