【问题标题】:Multiple CTEs with ArelArel 的多个 CTE
【发布时间】:2017-07-13 21:42:36
【问题描述】:

我有一个如下格式的 sql 查询:

 with from as (#{select * query}),
 to as (#{another select *}),
 rates as (#{yet another select *})
 select rates.* from rates, from, to
 where rates.from_id = from.id and rates.to_id = to.id

如何将其转换为 Arel?我查看了 Arel CTE,但没有像上面查询中那样使用多个别名的示例。

【问题讨论】:

标签: ruby-on-rails activerecord arel


【解决方案1】:

这应该可以解决问题:

from_table = Arel::Table.new(:from)
to_table = Arel::Table.new(:to)
rates_table = Arel::Table.new(:rates)
query = rates_table.
  join(from_table).on(rates_table[:from_id].eq(from_table[:id])).
  join(to_table).on(rates_table[:to_id].eq(to_table[:id])).
  project(rates_table[Arel.star]).
  with([
    Arel::Nodes::As.new(from_table, Arel::Nodes::SqlLiteral.new("select * query")),
    Arel::Nodes::As.new(to_table, Arel::Nodes::SqlLiteral.new("another select *")),
    Arel::Nodes::As.new(rates_table, Arel::Nodes::SqlLiteral.new("yet another select *")),
  ])
puts query.to_sql

您应该用实际的 Arel 查询替换 Arel::Nodes::SqlLiteral.new("another select *") 表达式。要从 ActiveRecord 关系中获取 Arel 查询,您可以在其上调用 .ast。示例:User.where(active: true).ast

【讨论】:

猜你喜欢
  • 2018-02-27
  • 1970-01-01
  • 2021-03-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-06-03
  • 2016-05-16
相关资源
最近更新 更多