无法使用 Arel 以编程方式组合 AND 和 OR 条件 [英] Cannot programmatically combine AND and OR conditions using Arel

查看:35
本文介绍了无法使用 Arel 以编程方式组合 AND 和 OR 条件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

鉴于使用 Arel 运算符(例如.eq)生成的 SQL 条件 cond1、cond2 和 cond3,我似乎无法使用 Arel 生成 SQL:

Given the SQL conditions cond1, cond2 and cond3 generated using Arel operators (.eq for example), I cannot seem to use Arel to produce the SQL:

SELECT * FROM <table> WHERE (cond1 AND cond2) OR cond3

这是因为将 AND 条件放在一起使用 .where(),但不能将 .or() 用于 .where() 的结果.您只能在 .where() 中将 .or() 条件组合在一起.IE..where 和 .or 不在同一个级别"上,我想人们需要一个与 .or() 处于同一级别的专用 .and() 方法.

This is because to AND conditions together you use .where(), but you can't then .or() the result of .where(). You can only .or() conditions together inside a .where(). I.e. .where and .or are not on the same "level", I would guess one needs a dedicated .and() method on the same level as .or().

请注意,(cond1 AND cond2) 周围的括号表示这些条件同时进行 AND 运算,其中 OR cond3 是在循环的另一次迭代中添加的.它们对查询结果没有影响.

Note that the brackets around (cond1 AND cond2) denotes that these conditions are ANDed together at the same time, where the OR cond3 is added in another iteration of the loop. They make no difference to the result of the query.

我已经阅读了 Arel README,但没有针对这种情况的示例,我无法弄清楚如何使用 Squeel 动态构建此查询(在循环中),它具有 OR 运算符 |.

I've read the Arel README and there is no example for this situation and I can't figure out how to dynamically build up this query (in a loop) using Squeel, which has an OR operator |.

推荐答案

Arel::Nodes::Grouping 将节点括在括号中.

Arel::Nodes::Grouping wraps nodes in parentheses.

Arel::Nodes::Grouping.new(Arel::Nodes::And.new("blah", "there")).to_sql
# => ('blah' AND 'there')

这篇关于无法使用 Arel 以编程方式组合 AND 和 OR 条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆