ruby-on-rails - ActiveRecord 获取具有一组特定相关模型的所有模型(AND 不是 OR)
问题描述
我有一个汽车数据库,这些汽车具有特定的功能(如座椅加热、LED 灯、交流电……)。
模型设置如下:
class Car < ApplicationRecord
has_many :car_key_features
has_many :key_features, through: :car_key_features
end
class CarKeyFeature < ApplicationRecord
belongs_to :car
belongs_to :key_feature
end
class KeyFeature < ApplicationRecord
has_many :car_key_features
has_many :cars, through: :car_key_features
end
我现在想获得所有具有特定功能的汽车。例如,我想获得所有具有标识符“座椅加热”和“led-lights”功能的汽车(但它也可能具有附加功能)。
我使用以下查询进行了尝试,但这为我提供了至少具有其中一项功能的所有汽车,而不是所有汽车(因为它会导致 SQL“IN”查询):
scope :by_key_features, ->(identifiers) { joins(:key_features).where(key_features: { identifier: identifiers }).group('cars.id') }
对此的任何帮助将不胜感激!
解决方案
您的查询将选择至少具有一项匹配功能的所有汽车。因此,您只需要选择与查询中所有特征数量相同的汽车。
scope :by_key_features, ->(identifiers) {
joins(:key_features)
.where(key_features: { identifier: identifiers })
.group('cars.id')
.having('COUNT(key_features.id) >= ?', identifiers.size)
}
推荐阅读
- r - loadNamespace (j <- i[[1L]], c(lib.loc, .libPaths()), versionCheck = vI[[j]]) 中的“汽车”的“Rcmdr”错误加载失败:
- forms - Symfony 4 中 FormErrorSerializer 的单元测试 - 始终有效的形式
- xamarin - Xamarin 应用程序基于 VS2017 而不是 VS for Mac 构建
- c# - 如何使用 C# 批量上传到 AWS S3
- html - 如何没有按钮 shift css
- python - 如果条件适用,交换两列数据框的值(Python 3)
- php - 如何从mysql数据库中查询两张表中的数据并显示一张HTML表
- python - 如何使用 PyRevit 获取用户输入?
- php - PHP MySql 查询获取每个用户的总和
- javascript - JS:重复字符串(Hackerrank Challenge)