【问题标题】:How to filter out values with 0 has_and_belongs_to_many relationships?如何过滤掉具有 0 has_and_belongs_to_many 关系的值?
【发布时间】:2021-01-18 23:36:36
【问题描述】:

我有两个documents

class Tag
  # ...
  store_in collection: :tags
  has_and_belongs_to_many :offices, class_name: 'Office'
end

class Office
  # ...
  store_in collection: :offices
  has_and_belongs_to_many :tags, class_name: 'Tag'
end

所有标签_id 都存储在mongodboffices 集合中的数组中

在下面的查询中,我需要过滤掉任何办公室不存在的任何标签,我的第一反应是将Tag.all 响应转换为数组,然后手动过滤掉值。 我不认为这是不可能的,因为我使用kaminari 进行 REST API 分页。

## ...

tags = Tag.all

## need to filter out tags with tag.offices.count.zero?
## ...

return tags.page(n).per(25)

【问题讨论】:

  • Tag.where(office_ids: {'$size'=>0})
  • 不幸的是,模型没有将office_ids保存到Tag,标签的id存储在办公室@D.SM
  • 标签上不存储office id怎么办?
  • @D.SM 我相信自动保存需要在 office 的 has_and_belongs_to_many 中打开,以便在创建/更新 office 时更新标签记录
  • 您有此行为的文档参考吗?

标签: ruby mongoid


【解决方案1】:

您可以使用tags = Tag.joins(:offices)。这将执行 INNER JOIN,并且只会返回与 office 相关联的标签。

【讨论】:

  • 我相信新版本的 mongoid 支持这一点,我使用的是6.4
猜你喜欢
  • 1970-01-01
  • 2017-09-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-09-29
相关资源
最近更新 更多