繁体   English   中英

Rails ActiveRecord where或clause

[英]Rails ActiveRecord where or 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 )

此查询通过组合categoriescategory_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(',')})")

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM