使用Arel表达CTE [英] Express a CTE using Arel

查看:96
本文介绍了使用Arel表达CTE的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下ActiveRecord片段:

I have this snippet of ActiveRecord:

scope = Listing.where(Listing.arel_table[:price].gt(6_000_000))

生成的sql:

SELECT listings.* FROM listings where listings.price > 6000000

我想添加一个CTE来生成此sql:

I would like to add a CTE that would result in this sql:

WITH lookup AS (
    SELECT the_geom FROM lookup WHERE slug = 'foo-bar'
)

SELECT * from listings, lookup
WHERE listings.price > 6000000
AND ST_within(listings.the_geom, lookup.the_geom)

我想表示此sql包含使用 Arel ActiveRecord 的CTE。

I would like to express this sql inclusive of the CTE using Arel and ActiveRecord.

我也想使用 scope 变量作为起点。

I would also like to use the scope variable as a starting point.

推荐答案

您可以像这样创建CTE:

You can create the CTE like:

lookup = Arel::Table.new(:lookup) # Lookup.arel_table
cte = Arel::Nodes::As.new(lookup,
  lookup.where(lookup[:slug].eq('foo-bar')).project('the_geom'))

,然后将其与您的范围一起使用,例如:

and then use it with your scope like:

scope.with(cte)

您可以在 Arel自述文件,在最底部

这篇关于使用Arel表达CTE的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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