【问题标题】:ActiveRecord query with find_by_sql on postgis data使用 find_by_sql 对 postgis 数据进行 ActiveRecord 查询
【发布时间】:2019-04-11 16:43:18
【问题描述】:

迄今为止,我只能运行涉及两个表的所有记录的 find_by_sql 查询来查找相交。

Regionpolygon.where('nation_id = ?', 74).find_by_sql "SELECT regionpolygons.id, area_name, destinations.id 
  FROM regionpolygons, destinations 
  WHERE ST_Intersects(regionpolygons.polygon_area, destinations.latlon)"

需要实现的两个目标是:

  • 有一个较小的子集可以从中查询 regionpolygons @rps = Regionpolygon.where('nation_id = ?',74).all 这似乎可行..
  • 从目标表@dests = Destination.all @dests.each do |dest| [...] 中提供一个点,以便迭代可以允许更新记录属性 添加到此类查询时,实例变量似乎没有被很好地消化

如何制定这个查询?

【问题讨论】:

    标签: ruby-on-rails postgis


    【解决方案1】:

    您的问题有点不清楚,但您只是在寻找一种可管理且程序化的方式来生成该查询,您可以使用arel 执行此搜索,如下所示

    rp_table = Regionpolygon.arel_table
    destination_table = Destination.arel_table
    
    query = rp_table.project(rp_table[:id], 
               rp_table[:area_name], 
               destination_table[:id].as('destination_id')
       ).join(destination_table).on(
           Arel::Nodes::NamedFunction.new('ST_Intersects', 
             [rp_table[:polygon_area], destination_table[:latlon]]
           )
       ).where(rp_table[:nation_id].eq(74))
    

    这将产生以下 SQL

    SELECT 
        [regionpolygons].[id], 
        [regionpolygons].[area_name], 
        [destinations].[id] AS destination_id 
    FROM 
        [regionpolygons] 
        INNER JOIN [destinations] ON 
            ST_Intersects([regionpolygons].[polygon_area], [destinations].[latlon])     
    WHERE 
        [regionpolygons].[nation_id] = 74
    

    您可以通过直接调用to_sqlquery 转换为SQL。所以:

    ActiveRecord::Base.connection.exec_query(query.to_sql).to_hash
    

    将返回它找到的行的Array,其中行被转换为哈希。这个哈希看起来像:

     {"id" => 1, "area_name" => "area_name", "destination_id" => 1} 
    

    【讨论】:

    • 由于目标是遍历集合,我将 where 子句修改为 ).where(rp_table[:nation].eq(74).and(destination_table[:id].eq(4079)))。非常明确且有用的答案; 我完全忽略了 AREL,但想知道为什么 find_by_sql 如此“无范围”...
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-19
    • 2018-01-27
    • 2010-10-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多