Arel 的多个 CTE
Multiple CTEs with Arel
我有一个 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,但没有像上面的查询那样使用多个别名的示例。
这应该可以解决问题:
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::Nodes::SqlLiteral.new("another select *")
表达式替换为实际的 Arel 查询。要从 ActiveRecord 关系中获取 Arel 查询,您可以对其调用 .ast
。示例:User.where(active: true).ast
.
我有一个 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,但没有像上面的查询那样使用多个别名的示例。
这应该可以解决问题:
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::Nodes::SqlLiteral.new("another select *")
表达式替换为实际的 Arel 查询。要从 ActiveRecord 关系中获取 Arel 查询,您可以对其调用 .ast
。示例:User.where(active: true).ast
.