我想找到courses
其中至少有 1variant
with variant_type
= 1 并且没有任何variant
with variant_type
= 2.
所以我的查询如下:
Course.where("id IN ( SELECT course_id
FROM course_variants
WHERE variant_type = 1
)
AND id NOT IN (
SELECT course_id
FROM course_variants
WHERE variant_type = 2
)")
另外,一个course
有很多course_variants
.
我在 where 子句中使用原始查询,我想使用 Active record 接口或 Arel 来改进它,有什么解决方案吗?
谢谢你!
使用输入更新预期输出
Input
course: {id=1, course_variants: [{variant_type: 1}, {variant_type: 2}]}
course: {id=2, course_variants: [{variant_type: 1}, {variant_type: 3}]}
course: {id=3, course_variants: [{variant_type: 2}, {variant_type: 3}]}
Output
course: {id=2, course_variants: [{variant_type: 1}, {variant_type: 3}]}
您可以稍微调整您的模型关联:
class Course < ActiveRecord::Base
has_many :type_1_variants, class_name: "CourseVariant", -> { where(variant_type: 1) }
has_many :non_type_3_variants, class_name: "CourseVariant", -> { where.not(variant_type: 3) }
end
Course.joins(:type_1_variants, :non_type_3_variants).group(:course_id).having('COUNT(course_variants.id) > 0').having('COUNT(non_type_3_variants_courses.id) > 0')
您可能需要将“non_type_3_variants_courses”替换为 ARel 在进行连接时生成的正确别名(我没有 Rails env atm)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)