繁体   English   中英

Ruby On Rails + PostgreSQL:如何从表 A 中获取所有在表 B 中没有关联的记录?

[英]Ruby On Rails + PostgreSQL: How to get all records from table A that don't have association in table B?

我有这两个模型:

class ModelA < ApplicationRecord
  has_one :model_b
end

class ModelB < ApplicationRecord
  belongs_to :model_a
end

我需要从表 model_a 中获取所有在表model_a中没有匹配记录的model_b ——无论是通过 AR 还是原始 PostgreSQL 查询。

最优雅/最有效的方法是什么?

我能想到的只是循环遍历model_a并在model_b中搜索匹配的记录。

先感谢您。

你试过LEFT JOIN吗? 就像是

ModelA.left_joins(:model_b).where(table_model_b: {model_a_id: nil})

如果我的想法正确,您可以尝试只排除具有关系的 ID

ModelA.where.not(id: ModelB.pluck(:model_a_id).uniq)

为了便于理解:

model_b_ids = ModelB.all.pluck(:id)
ModelA.where('model_b_id NOT IN (?)', model_b_ids)

您必须尝试对表 b 中的 A_id 进行左连接和过滤。

ModelA.left_joins(:ModelB).where("model_B.model_a_id": nil)

ModelA.left_joins(:ModelB).where(model_B: { model_a_id: nil })

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM