[英]ActiveRecord OR Query in Arel
對於簡單查詢,可以在ActiveRecord中進行OR查詢,如下所示:
Model.where({:category => "XYZ", :item_id => some_ids})
=>
table = Model.arel_table
Model.where(table[:category].eq("XYZ").or(table[:item_id].in(some_ids)))
結果不是非常緊湊和清晰。 如果您有更復雜的查詢,在Arel中編寫以下ActiveRecord查詢也可能並且有用嗎?
Model.where(["(item_id = ? AND item_type = 'ABC') OR
(item_id IN (?) AND item_type = 'XYZ')",id,more_ids]).
order("created_at DESC")
怎么樣:
first_part = arel_table[:item_id].eq(id).and(arel_table[:item_type].eq('ABC'))
second_part = arel_table[:item_id].in(more_ids).and(arel_table[item_type].eq('XYZ'))
Model.where(first_part.or(second_part)).order(created_at: :desc)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.