简体   繁体   English

Laravel 5.5 查询生成器 whereRaw 不返回结果但原始 SQL 返回

[英]Laravel 5.5 Query Builder whereRaw returns no results but raw SQL does

When I perform the scoped query below I get no results, yet when I execute the resulting SQL (with bindings transcribed) on the database I get the expected results.当我执行下面的范围查询时,我没有得到任何结果,但是当我在数据库上执行结果 SQL(带有转录的绑定)时,我得到了预期的结果。 I can query the model without the scope and the results are as expected.我可以在没有范围的情况下查询模型,结果符合预期。

It's a straightforward query checking whether a point exists within a polygon.这是一个简单的查询,检查多边形内是否存在一个点。 I see no signs of errors or exceptions.我没有看到错误或异常的迹象。 I'm at a loss.我不知所措。 Am I missing something?我错过了什么吗?

Area Class (w/ Query Scope):区域类(带查询范围):

namespace App;

use Illuminate\Database\Eloquent\Model;
use Grimzy\LaravelMysqlSpatial\Eloquent\SpatialTrait;
use Grimzy\LaravelMysqlSpatial\Types\Point;
use Grimzy\LaravelMysqlSpatial\Types\Polygon;
use Grimzy\LaravelMysqlSpatial\Types\Linestring;

class Area extends Model
{
    use SpatialTrait;

    protected $table = "areas";

    protected $spatialFields = [
        'point',    // MySQL POINT type
        'area'      // MySQL POLYGON type
    ];

    public function scopeContainsPoint($query, $lat, $lng) {
        return $query->whereRaw("ST_Contains(area, GeomFromText('POINT(? ?)'))", [$lng, $lat]);
    }

}

Query Scope Usage and Results:查询范围使用和结果:

$s = Area::containsPoint(43.80, -79.48)->get();

=> Illuminate\Database\Eloquent\Collection {#3192
     all: [],
   }

Eloquent Query Log:雄辩的查询日志:

DB::getQueryLog();
=> [
     [
       "query" => "select * from `areas` where ST_Contains(area, GeomFromText('POINT(? ?)'))",
       "bindings" => [
         -79.48,
         43.8,
       ],
       "time" => 311.05,
     ],
   ]

Resuting SQL (returns correct result):恢复 SQL(返回正确结果):

select * from `areas` where ST_Contains(area, GeomFromText('POINT(-79.48 43.8)'));

The problem boiled down to an issue escaping the 'POINT(-79.48 43.8)' portion of the raw DB statement that for some reason didn't reveal itself on the DB::getQueryLog() .问题归结为逃避原始 DB 语句的'POINT(-79.48 43.8)'部分的问题,由于某种原因,它没有在DB::getQueryLog()上显示出来。

Changing from:更改自:

$query->whereRaw("ST_Contains(area, GeomFromText('POINT(? ?)'))", [$lng, $lat]);

to this:对此:

$query->whereRaw("ST_Contains(area, GeomFromText(?))", ["POINT($lng $lat)"]);

resolved the problem and returns the expected rows.解决了问题并返回了预期的行。

Edit: Also, for anyone wondering - I discovered that the Grimzy/laravel-mysql-spatial library contains the scope I was looking for (among many others).编辑:另外,对于任何想知道的人 - 我发现Grimzy/laravel-mysql-spatial库包含我正在寻找的范围(以及许多其他范围)。 Still learned something about prepared statements though.尽管如此,仍然学到了一些关于准备好的语句的知识。 Always read the manual.始终阅读手册。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM