在postgis数据上使用find_by_sql进行ActiveRecord查询

问题描述 投票:0回答:1

到目前为止,我只能运行一个find_by_sql查询,该查询涉及两个表的所有记录以查找Intersects。

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个回答
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

你可以通过字面上调用queryto_sql转换为SQL。所以:

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

将返回它发现执行上述行的Array,其中行被转换为哈希值。这个哈希看起来像:

 {"id" => 1, "area_name" => "area_name", "destination_id" => 1} 
© www.soinside.com 2019 - 2024. All rights reserved.