donkey199024 2018-11-26 08:58
浏览 82

Laravel / Eloquent - 无法执行原始查询

This is the function that is executing the query:

    public static function getNearbyCityReport(float $lon, float $lat, float $rangeInKm){
    $query = "
        SELECT
            name,
            population,
            round((ST_Distance(rpoint, 'POINT( ? ? )', True)/1000)::numeric, 1) as distance,
            round(degrees(ST_Azimuth(rpoint, 'POINT( ? ? )'))::numeric,1) AS azimuth
        FROM
            gis_cities
        WHERE
            ST_DWithin(rpoint, 'POINT( ? ? )', 1000*?, True)
            AND
            feature_code != 'PPLX'
        ORDER BY distance;        
    ";
    $query = preg_replace('#
#', ' ', $query);
    $query = trim(preg_replace('#\s{2,}#', ' ', $query));
    $expression = DB::raw($query);
    $result = DB::select($expression, [$lon, $lat, $lon, $lat, $lon, $lat, $rangeInKm]);
    dd($result);

When running this function I get the following exception:

SQLSTATE[HY093]: Invalid parameter number: parameter was not defined (SQL: SELECT name, population, round((ST_Distance(rpoint, 'POINT( 24.8 43.3648 )', True)/1000)::numeric, 1) as distance, round(degrees(ST_Azimuth(rpoint, 'POINT( 24.8 43.3648 )'))::numeric,1) AS azimuth FROM gis_cities WHERE ST_DWithin(rpoint, 'POINT( 24.8 43.3648 )', 1000*300, True) AND feature_code != 'PPLX' ORDER BY distance;)

The weird thing is that nothing seems to be missing from the built query shown in the exception and if I run that query on my database it works properly. How can I make this work?

LATER EDIT:

Apparently the problem actually lies at PDO level and is caused by the fact that I am trying to add some parameters inside a quoted string:

(ST_Distance(rpoint, 'POINT( ? ? )', True)/1000)

See the 'POINT( ? ? )' parts. If I remove all the quotes from my query then it works but of course it is not a valid postgis query anymore. Anybody know how this query should be written so that PDO will accept it ?

  • 写回答

1条回答 默认 最新

  • douyinliu8813 2018-11-26 12:13
    关注

    You have to merge the two coordinates into a single binding:

    (ST_Distance(rpoint, 'POINT( ? )', True)/1000)
    
    $result = DB::select($expression, [$lon.' '.$lat, ...]);
    
    评论

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度