我有 Bike
和 Category
模型。通过 BikeFilter
模型自行车 has_many 类别。
问题是,通过搜索,我得到了 5 个不同的类别,而我只需要找到这些自行车,这些自行车在 BikeFilter
表中都有所有 5 个类别的记录。
如果我在 mysql 中执行 GROUP BY,它也会选择在 bike_filters
中只有 1 个或几个类别的记录。并且需要谁拥有所有这些。
自行车.rb
has_many :bike_filters
has_many :categories, :through => :bike_filters
自行车过滤器.rb
belongs_to :category
belongs_to :bike
最佳答案
您可以使用having
子句:
http://guides.rubyonrails.org/active_record_querying.html#having
并执行如下操作:
Bike.select("bikes.*, count(*) as num_of_categories")
.joins(:categories)
.where(categories: { id: cats })
.group("bikes.id")
.having("num_of_categories = ?", cats.length)
此查询将首先在 Bike 和 Category 之间执行 Inner Join(通过 BikeFilter 表),然后它将仅选择 cats
数组中包含category_id 的行。
此时,查询将根据自行车 ID 对所有记录进行分组,并仅返回行数等于类别数的组。
一些注释:
- 仅当(bike_id,category_id)对在 BikeFilter 表中唯一时,此方法才有效。
- 此查询将返回与所有给定类别关联的所有自行车,无论它们是否具有与其关联的其他类别。
关于ruby-on-rails - 使用关联过滤逻辑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35009393/