假设以下模型:
class Product
include MongoMapper::Document
key :name, String
key :product_category_id, ObjectId
belongs_to :product_category
end
class ProductCategory
include MongoMapper::Document
key :name, String, :required => true, :unique => true
timestamps!
userstamps!
end
我想实现一个高级搜索,它将检查我的模型中的所有值,包括它的所有关联,如: 我有:
当我使用名为“Notebook”的关键字进行搜索时,我想将其搜索到Product.name字段以及它们也指代ProductCategory.name的关联。因此,它将返回这两个项目,因为产品A具有ProductCategory.name“Notebook”&产品B有Product.name“aGreatNotebook”和ProductCategory“Notebook”..
我该怎么做?我已经搜索了2天,直到现在才成功:( ..当在MySQL中时,我使用了连接表..但是在MongoMapper中怎么样?
请帮忙......谢谢..
答案 0 :(得分:0)
您无法在MongoDB中进行加入。因此,基本思想是将ObjectId与“Notebook”类别相关联,然后查询product_category等于notebook_id的产品。这通常涉及两个查询。所以这就是这样的:
notebook_id = ProductCategory.first(:name => "Notebook")
if notebook_id
Product.where({:product_category_id => notebook_id['_id']})
end
答案 1 :(得分:0)
这个问题令人困惑,但是问题的标题很清楚。
所以,如果有人来这里希望看到如何获得所有这些东西:
继续阅读...
要获取模型中的键:
ConfinedSpace.keys.keys
=> ["_id", "photo_ids", "include_in_qap", "position", "created_at", "updated_at",
"structure_id", "identifier", "name", "description", "notes", "entry_info",
"anchor_points", "nature", "special_equipment", "rescue_overview"]
并获得关联:
ConfinedSpace.associations.each{|name,assoc| puts name}
photos
attachments
activities
structure
videos
以及班级(为简洁起见进行编辑):
class ConfinedSpace
include MongoMapper::EmbeddedDocument
include Shared::HasPhotos
include Shared::HasAttachments
include HasActivities
TAG = "ConfinedSpace"
belongs_to :structure
many :videos, :as => :attachable
key :identifier, String
key :name, String
key :description, String
key :notes, String
key :entry_info, String
key :anchor_points, String
key :nature, String
key :special_equipment, String
key :rescue_overview, String
validates :identifier, presence: true
end