0

我想拉出所有至少有一个“CEO”职位头衔的公司。

我可以将它与每个表的查询和一个相交一起破解(我知道......没有连接http://mongoid.org/en/mongoid/docs/tips.html#relational_associationsmongoid 中的 N+1 问题,我可以在公司中嵌入职位),但是可以通过任何方式执行以下操作:

Company.includes(:positions).where("positions.title" => "CEO")?

谢谢:

class Position
  include Mongoid::Document

  field :title, type: String
  field :profile_id, type: String
  field :tenure, type: BigDecimal

  belongs_to :company, index: true

class Company
  include Mongoid::Document

  field :name, type: String
  field :linkedin_id, type: String
  field :positions_count, type: Integer #Mongo Index

  belongs_to :industry, index: true
  has_many :positions

  index({ positions_count: 1}, {background: true})
4

1 回答 1

1

为避免 N+1 问题,启用 Mongoid identity_map 功能

这将允许您执行以下查询:

companies_with_ceo = Position.where(title: 'CEO').includes(:company).map(&:company)

应该只对数据库执行 2 个查询。

于 2012-12-06T20:45:35.567 回答