Rails ActiveRecord where或clause
我正在寻找一个ActiveRecord查询,这就是我在下面的内容。 不幸的是你不能像这样使用OR。 什么是最好的执行方式? category_ids
是一个整数数组。
.where(:"categories.id" => category_ids).or.where(:"category_relationships.category_id" => category_ids)
一种方法是恢复原始sql …
YourModel.where("categories.id IN ? OR category_relationships.category_id IN ?", category_ids, category_ids)
保持SQL不受它影响并使用ARel,如下所示:
.where(Category.arel_table[:id].in(category_ids). or(CategoryRelationship.arel_table[:category_id].in(category_ids))
假设您要返回Categories,则需要OUTER JOIN category_relationships并在组合表上放置OR条件。
Category.includes(:category_relationships).where("categories.id IN (?) OR category_relationships.category_id IN (?)",category_ids,category_ids )
此查询通过组合categories
和category_relationships
列来创建外部联接表。 与内部联接(例如, Category.joins(:category_relationships)
)不同,外部联接表也categories
具有没有关联的category_relationship
。 然后,它将在外连接表的where
子句中应用条件以返回匹配的记录。
includes
无关联条件的语句通常会使两个单独的sql查询检索记录及其关联。 但是,当与关联表上的条件一起使用时,它将进行单个查询以创建外部联接表并在外部联接表上运行条件。 这允许您检索没有关联的记录。
有关详细说明,请参阅此处。
你想要做的是手动编写查询的OR部分,如下所示:
.where("category.id in (#{category_ids.join(',')}) OR category_relationships.category_id in (#{category_ids.join(',')})")