gpt4 book ai didi

ruby-on-rails - Rails/Arel - 组合 AREL 谓词时的优先级

转载 作者:行者123 更新时间:2023-12-04 03:37:44 25 4
gpt4 key购买 nike

一个模型有两个感兴趣的属性,名字和城镇。我想搜索 Richard(伦敦)和 Brian(马德里)。

从长远来看,

p=Person.scoped
pred1=p.table[:forename].eq('Richard').and(p.table[:town].eq('London'))
pred2=p.table[:forename].eq('Brian').and(p.table[:town].eq('Madrid'))
pred3=pred1.or(pred2)

我希望这将谓词包装在括号中以保持查询的完整性。但是查看 pred3.to_sql 给出了意外的响应:
"(`person`.`forename` = 'Richard' AND `person`.`town` = 'London' OR `person`.`forename` = 'Brian' AND `person`.`town` = 'Madrid')"

如何让 Arel 生成正确的查询?

最佳答案

这实际上是正确的查询,因为在大多数 SQL 方言中,AND 的运算符优先级高于 OR。如果要翻转它和 AND 2 OR 谓词,它会将 OR 谓词包装在括号中。

t = Arel::Table.new('blah')

a = (t[:a].eq(nil).and(t[:b].eq(nil)))
b = (t[:a].not_eq(nil).and(t[:b].not_eq(nil)))
a.or(b).to_sql

=> "(`blah`.`a` IS NULL AND `blah`.`b` IS NULL OR `blah`.`a` IS NOT NULL AND `blah`.`b` IS NOT NULL)"

a = (t[:a].eq(nil).or(t[:b].eq(nil)))
b = (t[:a].not_eq(nil).or(t[:b].not_eq(nil)))
a.and(b).to_sql

=> "(`blah`.`a` IS NULL OR `blah`.`b` IS NULL) AND (`blah`.`a` IS NOT NULL OR `blah`.`b` IS NOT NULL)"

关于ruby-on-rails - Rails/Arel - 组合 AREL 谓词时的优先级,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6523810/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com