【问题标题】:Mongoid query using 1:M relationship使用 1:M 关系的 Mongoid 查询
【发布时间】:2018-11-30 06:00:54
【问题描述】:

我有一个集合 A 和一个集合 B

在我声明的模型 A 中 - has_many: B

在模型 B 中我已声明 - belongs_to: A

所以我可以像“A.B”一样查询,它返回与 A 关联的所有 B。

如何查询以仅选择 A.B.size 为 0 的 A

例如:A.where(some_condition).and(:A.B.size => 0)

【问题讨论】:

    标签: mongoid


    【解决方案1】:

    A=A 的集合名称 B = B 的集合名称

    首先我们将获取插入到 B 中的 A 的所有唯一外键。

    data_in_b = B.where(condition).pluck(:a_id)
    a_ids = A.all.pluck(:_id) // ["id1", "id2", "id3", "id4", "id5"]
    if data_in_b.count > 0 
        a_fks_in_b = data_in_b.uniq // ["id1", "id5"]
        ids_in_a_without_b = a_ids - a_fks_in_b // ["id2", "id3", "id5"]
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-26
      • 2013-02-22
      • 2018-08-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多