rails mongoid 找到 parent 和 child
rails mongoid find parent with child
快速示例,
class Band
include Mongoid::Document
embeds_many :albums
end
class Album
include Mongoid::Document
field :name, type: String
embedded_in :band
end
文档将如下所示,
{
"_id" : ObjectId("4d3ed089fb60ab534684b7e9"),
"albums" : [
{
"_id" : ObjectId("4d3ed089fb60ab534684b7e0"),
"name" : "Violator",
}
]
}
假设,我想创建一个方法来找到 Band with albums name
如果这是 ActiveRecord
,那就简单了
Album.find_by(name: "Violator").band
但是像这样的情况呢?
我是否必须遍历整个集合并像这样找到它?
Band.select {|band| band.albums.select{|album| album.name == "Violator"}}
听起来很疯狂...
或者我是否必须使用 Referenced relations
而不是 Embedded relations
进行数据建模?
嵌入式文档最适合不需要独立查询的项目。如果您需要独立查询某些内容,请考虑使用引用。在您的情况下,您可以先使用特定的专辑名称找到乐队,然后再处理这些乐队
@bands = Band.where("albums.name" => "Violator")
@albums = @bands.collect{|band| band.albums.where(name: 'Violator') }.flatten
这里有关于 mongoid 关系的更多细节http://mongoid.org/en/mongoid/docs/relations.html
快速示例,
class Band
include Mongoid::Document
embeds_many :albums
end
class Album
include Mongoid::Document
field :name, type: String
embedded_in :band
end
文档将如下所示,
{
"_id" : ObjectId("4d3ed089fb60ab534684b7e9"),
"albums" : [
{
"_id" : ObjectId("4d3ed089fb60ab534684b7e0"),
"name" : "Violator",
}
]
}
假设,我想创建一个方法来找到 Band with albums name
如果这是 ActiveRecord
,那就简单了
Album.find_by(name: "Violator").band
但是像这样的情况呢?
我是否必须遍历整个集合并像这样找到它?
Band.select {|band| band.albums.select{|album| album.name == "Violator"}}
听起来很疯狂...
或者我是否必须使用 Referenced relations
而不是 Embedded relations
进行数据建模?
嵌入式文档最适合不需要独立查询的项目。如果您需要独立查询某些内容,请考虑使用引用。在您的情况下,您可以先使用特定的专辑名称找到乐队,然后再处理这些乐队
@bands = Band.where("albums.name" => "Violator")
@albums = @bands.collect{|band| band.albums.where(name: 'Violator') }.flatten
这里有关于 mongoid 关系的更多细节http://mongoid.org/en/mongoid/docs/relations.html