Rails – SQL查询返回所有指定相关对象的对象(has_many through)
这是我的第一个问题。
我想构建一个查询,它将为我提供具有所有指定function的所有主题。
我有三个模型主题,function和ThemeFeatures
主题has_many:features,:through =>:theme_feautures
可以说DB中有一个Theme对象(id:1,name:“theme_a”)。 它有(许多)function[(id:1,name:“feature_a”),(id:2,name:“feature_b”),(id:3,name:“feature_c”)]
查询应该像这样工作:Theme.the_query(:features => {:id => [1,2]}),结果是主题,但是当我以这种方式放置ID时Theme.the_query(:features => {:id => [2,4]})结果应为零。
我已经构建了Theme.joins(:features).where(:features => {:id => features_array_ids})但它返回了所有具有features_array_ids元素的主题。 如果features_array_ids = [2,4]它返回主题,但我不希望这样。
对于语法错误我很抱歉,我希望你知道我的意思。
编辑:
找到解决方案
Theme.select("*").from("themes").joins("INNER JOIN theme_features ON themes.id = theme_features.id").where("EXISTS(SELECT theme_id FROM theme_features tf WHERE tf.feature_id IN (#{features_array_ids.join(", ")}) AND tf.theme_id = themes.id GROUP BY tf.theme_id HAVING COUNT(*) = #{features_array_ids.count})")
解。
Theme.select("*").from("themes").joins("INNER JOIN theme_features ON themes.id = theme_features.theme_id").where("EXISTS(SELECT theme_id FROM theme_features tf WHERE tf.feature_id IN (#{features_array_ids.join(", ")}) AND tf.theme_id = themes.id GROUP BY tf.theme_id HAVING COUNT(*) = #{features_array_ids.count})")
- 独特的加入Rails
- accept_nested_attributes_for:allow_destroy,:_ destroy无效
- 手动更新模型后更新db / migrate?
- Rails ActiveRecord关系助手如何允许诸如`user.groups.new`之类的方法?
- 模型属性不会更新,在不更新的单独属性上调用validation错误?
- Rails:从另一个模型调用一个模型。 为什么这不可能?
- 基于枚举值的自定义顺序
- RAILS:如何查询每个关联都具有非null属性的所有对象
- Rails 5 db migration:如何修复ActiveRecord :: ConcurrentMigrationError