如何通过两个引用查询Mongodb文档
How to query for Mongoid documents by two references
我在这个项目中使用 Mongoid。假设我有一个这样的模型:
class Voice
include Mongoid::Document
include Mongoid::Timestamps
include Mongoid::Enum
include Mongoid::Paperclip
enum :status, [:enabled, :disabled], :validate => true, :default => :enabled
...
has_and_belongs_to_many :categories
has_and_belongs_to_many :builder_types
has_and_belongs_to_many :voice_types
has_and_belongs_to_many :preferences
has_and_belongs_to_many :languages
embeds_many :comments
embeds_many :ratings
belongs_to :artist, :class_name => "User"
...
end
如您所见,Voice
拥有并属于 Category
、BuilderType
、VoiceType
等。目前,如果我想搜索属于特定类别的所有声音,我会执行以下操作(伪代码):
@category = Category.find(id)
@voices = @category.voices
效果很好。搜索具有或属于多个关系和关系类型的 Voice
如何? (无效的伪代码):
@cat1 = Category.find(id)
@cat2 = Category.find(id)
@voice_type = VoiceType.find(id)
@voices = @cat1.voices.where(category_id: @cat2.id).where(voice_type_id: @voice_type.id)
但这不起作用。如果 1) 完全有可能,以及 2) 我该怎么做,有什么想法吗?
这可能适合你:
Voice.all(category_ids: [@cat1.id, @cat2.id]).
where(:voice_type_ids.in [@voice_type.id])
为了以后参考,最后我做的是:
@voices = Voice.all(category_ids: [@cat_1.id, @cat_2.id]).
and(voice_type_ids: @voice_type.id).map{ |voice| voice.format_frontend }
我在这个项目中使用 Mongoid。假设我有一个这样的模型:
class Voice
include Mongoid::Document
include Mongoid::Timestamps
include Mongoid::Enum
include Mongoid::Paperclip
enum :status, [:enabled, :disabled], :validate => true, :default => :enabled
...
has_and_belongs_to_many :categories
has_and_belongs_to_many :builder_types
has_and_belongs_to_many :voice_types
has_and_belongs_to_many :preferences
has_and_belongs_to_many :languages
embeds_many :comments
embeds_many :ratings
belongs_to :artist, :class_name => "User"
...
end
如您所见,Voice
拥有并属于 Category
、BuilderType
、VoiceType
等。目前,如果我想搜索属于特定类别的所有声音,我会执行以下操作(伪代码):
@category = Category.find(id)
@voices = @category.voices
效果很好。搜索具有或属于多个关系和关系类型的 Voice
如何? (无效的伪代码):
@cat1 = Category.find(id)
@cat2 = Category.find(id)
@voice_type = VoiceType.find(id)
@voices = @cat1.voices.where(category_id: @cat2.id).where(voice_type_id: @voice_type.id)
但这不起作用。如果 1) 完全有可能,以及 2) 我该怎么做,有什么想法吗?
这可能适合你:
Voice.all(category_ids: [@cat1.id, @cat2.id]).
where(:voice_type_ids.in [@voice_type.id])
为了以后参考,最后我做的是:
@voices = Voice.all(category_ids: [@cat_1.id, @cat_2.id]).
and(voice_type_ids: @voice_type.id).map{ |voice| voice.format_frontend }