首页 > 解决方案 > 查找所有关联计数为零和非零的记录

问题描述

class Gallery < ApplicationRecord
  has_many :associated_images, as: :imageable
end

class Event < ApplicationRecord
  has_many :associated_images, as: :imageable
end

class Image < ApplicationRecord
  has_many :associated_images
end

class AssociatedImage < ApplicationRecord
  belongs_to :imageable, polymorphic: true
  belongs_to :image
end

我想获取所有正在使用的图像,以及一个不同的查询来获取所有未使用的图像(基于AssociatedImage)。

我试过Image.joins(:associated_images).group('images.id').having('count(image_id) > 0')了,它返回了正确的结果。但是当我运行时Image.joins(:associated_images).group('images.id').having('count(image_id) = 0'),它返回一个空#<ActiveRecord::Relation []>,我不知道为什么会这样。

我的查询基于查找所有关联计数大于零的记录的讨论

标签: sqlruby-on-railsactiverecord

解决方案


原因是在 SQL 中,当没有行时计数为零。因此,如果没有行,甚至没有组,就没有结果。

你想要的是

Image.left_joins(:associated_images).where(associated_images: {id: nil}).group('images.id')

当 SQL 进行左连接时,对于没有关联图像的图像,它会为表中的所有列填充 NULL associated_images。所以那些associated_images.id是零的,就是我们想要的。


推荐阅读