Sql 从数组中查找包含属性组合的所有记录
我有一个名为Sql 从数组中查找包含属性组合的所有记录,sql,ruby-on-rails,activerecord,ruby-on-rails-5,arel,Sql,Ruby On Rails,Activerecord,Ruby On Rails 5,Arel,我有一个名为LayerProducts的表,其中包含layer\u id和product\u id属性 我想创建一个查询,在这里我可以传入一个数组,如下所示: [ [:layer1_id, :product1_id], [:layer2_id, :product2_id], [:layer3_id, :product3_id] ] def self.for_multiple_lp(arr=[]) # Handle case when arr is not in the expected f
LayerProducts
的表,其中包含layer\u id
和product\u id
属性
我想创建一个查询,在这里我可以传入一个数组,如下所示:
[ [:layer1_id, :product1_id], [:layer2_id, :product2_id], [:layer3_id, :product3_id] ]
def self.for_multiple_lp(arr=[])
# Handle case when arr is not in the expected format.
condition = arr.collect{|a| "(layer_id = #{a[0]} AND product_id = #{a[1]})"}.join(" OR ")
where(condition)
end
并返回包含所提供的任何组合的LayerProduct
的所有记录
父数组不是固定长度的,因此查询需要是动态的,以适应任意数量的组合
这可能吗?如果可能,我将如何使用SQL或active record创建此查询?您可以构造原始SQL并使用active record。 大概是这样的:
[ [:layer1_id, :product1_id], [:layer2_id, :product2_id], [:layer3_id, :product3_id] ]
def self.for_multiple_lp(arr=[])
# Handle case when arr is not in the expected format.
condition = arr.collect{|a| "(layer_id = #{a[0]} AND product_id = #{a[1]})"}.join(" OR ")
where(condition)
end
对于没有activerecord的原始sql,您可以参考