【问题标题】:Mongoid Search by Array of Association Id's通过关联 ID 的数组进行 Mongoid 搜索
【发布时间】:2015-03-11 15:55:41
【问题描述】:

我有一个带有这些模型的 Rails 4.2、Mongoid 4 项目:

class Customer #aka Company
  include Mongoid::Document

  has_many :branches
end

class Branch
  include Mongoid::Document  

  field :name, type: String, default: ""

  belongs_to :customer
end

我想查找所有拥有名为“纽约”的分支机构的客户(也称为公司)。我认为这段代码会起作用:

branches = Branch.where(name: "New York").map(&:_id)
=> [BSON::ObjectId('54f76cef6272790316390100')]
Customer.where(:branch_ids => branches).entries

但是,无论我尝试什么,它总是返回一个空数组。代替branch_ids,我也尝试过branchesbranchbranches_id等,但无济于事。我也尝试将BSON::ObjectID 转换为普通的string,但这也不起作用。

那么,基本上,我如何根据关联 ID 数组搜索模型?谢谢。

【问题讨论】:

  • 返回什么:Customer.elem_match(branches: { name: "New York" })
  • 还有这个 - Customer.where(:branches.elem_match => { name: "New York" })
  • @SharvyAhmed 都返回一个空数组(在调用.entries 之后)
  • 你可以试试不带 .entries,最后试试 .to_a 让我们知道输出
  • 返回所有客户吗?

标签: ruby-on-rails mongoid mongoid4


【解决方案1】:

如果关系是

客户has_many :branches

分支belongs_to :customer,

然后分支集合将有一个customer_id 列,而不是相反。所以你可以做

cust_ids = Branch.where(name: "New York").map(&:customer_id)
Customer.find(cust_ids)

由于您只需要第一个查询中的客户 ID,因此建议使用 pluck

cust_ids = Branch.where(name: "New York").pluck(:customer_id)

【讨论】:

  • 这确实有效(不知道为什么我没有想到它),但它似乎是一种解决方法。我知道没有branch_ids的列,但是有一个方法。就是不知道能不能通过方法搜索。
【解决方案2】:

你可以像这样使用Symbol#elem_match

Customer.where(:branches.elem_match => { name: "New York" })

像这样Queryable#elem_match

Customer.elem_match(branches: { name: "New York" })

这两个查询都会为您返回“纽约”分支机构的客户。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-07-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-20
    • 1970-01-01
    相关资源
    最近更新 更多