MongoMapper中是否有一种方法可以实现与AR的include方法类似的行为? [英] Is there a way in MongoMapper to achieve similar behavior as AR's includes method?

查看:100
本文介绍了MongoMapper中是否有一种方法可以实现与AR的include方法类似的行为?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

MongoMapper中是否具有与之等效的功能:

Is there a feature equivalent in MongoMapper to this:

class Model < ActiveRecord::Base
  belongs_to :x
  scope :with_x, includes(:x)
end

运行Model.with_x时,可以避免对X进行N次查询。
MongoMapper中有类似的功能吗?

When running Model.with_x, this avoids N queries to X. Is there a similar feature in MongoMapper?

推荐答案

当属于属于关系时,可以打开身份地图,然后运行两个查询,一次查询您的主文档,然后一次查询所有关联的文档。这是您最好的选择,因为Mongo不支持联接。

When it's a belongs_to relationship, you can turn on the identity map and run two queries, once for your main documents and then one for all the associated documents. That's the best you can do since Mongo doesn't support joins.

class Comment
  include MongoMapper::Document
  belongs_to :user
end

class User
  include MongoMapper::Document
  plugin MongoMapper::Plugins::IdentityMap
end

@comments = my_post.comments                # query 1
users = User.find(@comments.map(&:user_id)) # query 2

@comments.each do |comment|
  comment.user.name # user pulled from identity map, no query fired
end

(Mongoid具有渴望加载的语法,但基本上可以同样的方式。)

(Mongoid has a syntax for eager loading, but it works basically the same way.)

这篇关于MongoMapper中是否有一种方法可以实现与AR的include方法类似的行为?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆