从CakePHP中的lat/lng获取附近数据

从CakePHP中的lat/lng获取附近数据,php,sql,cakephp,cakephp-2.4,Php,Sql,Cakephp,Cakephp 2.4,我正在尝试使用Euromark的地理编码行为(他的工具插件的一部分)在我的CakePHP 2.4.3应用程序中获取附近的帖子,但遇到了一个SQL错误。这是我的控制器代码: $this->Post->Behaviors->attach('Tools.Geocoder'); $this->Post->setDistanceAsVirtualField(44, 50); //or whatever coords $options = array(

我正在尝试使用Euromark的地理编码行为(他的工具插件的一部分)在我的CakePHP 2.4.3应用程序中获取附近的帖子,但遇到了一个SQL错误。这是我的控制器代码:

    $this->Post->Behaviors->attach('Tools.Geocoder');
    $this->Post->setDistanceAsVirtualField(44, 50);  //or whatever coords
    $options = array(
        'contain' => array(), //same error when I don't use this, just using it to keep the SQL query easier to read
        'order' => array('Post.distance' => 'ASC', 'limit' => 10)
    );
    $posts = $this->Post->find('all', $options);
    $this->set('posts', $posts);
这会抛出一个SQL错误;它说语法有问题:

SELECT 
    `Post`.`id`, `Post`.`lat`, `Post`.`lng`, `Post`.`body`, 
    (6371.04 * ACOS(
        COS(
            PI() / 2 - RADIANS(90 - `Post`.`lat`)
        ) * COS(
            PI() / 2 - RADIANS(90 - 44)
        ) * COS(
            RADIANS(`Post`.`lng`) - RADIANS(50)
        ) + SIN(
            PI() / 2 - RADIANS(90 - `Post`.`lat`)
        ) * SIN(
            PI() / 2 - RADIANS(90 - 44)
        )
    )) AS `Post__distance`
FROM `database`.`posts` AS `Post` 
WHERE 1 = 1 

ORDER BY 
    (6371.04 * ACOS(
        COS(
            PI() / 2 - RADIANS(90 - `Post`.`lat`)
        ) * COS(
            PI() / 2 - RADIANS(90 - 44)
        ) * COS(
            RADIANS(`Post`.`lng`) - RADIANS(50)
        ) + SIN(
            PI() / 2 - RADIANS(90 - `Post`.`lat`)
        ) * SIN(
            PI() / 2 - RADIANS(90 - 44)
        )
    )) ASC, 
`limit` 10

我使用的是最新版本的插件,上面说它是为Cake 2.x设计的。我的帖子将地理位置数据存储为
Post.lat
Post.lng
。知道它为什么会创建格式不正确的SQL吗?我的SQL技能是如此之强,以至于我无法发现错误,想必插件是正常的,我的控制器操作也有一些问题。

最后,ASC后面有一个逗号,限制在反勾号中。当Cake得到它不期望的参数时,它会对SQL查询做一些奇怪的事情。我怀疑你的问题在于:

'order' => array('Post.distance' => 'ASC', 'limit' => 10)
尝试:


基本上,数组的嵌套是错误的

'order' => array('Post.distance' => 'ASC', 'limit' => 10)
应为(注意右括号)


看起来它现在运行得很好:)PS:在较新的版本中,您可以使用load()而不是attach()。后者已被弃用。order的数组版本运行良好-如果右括号位于它们所属的位置….;)看看我的答案。嗨,马克。数组是不必要的,因为只传递了一个订单条件,这就是我删除它的原因。除了延长代码(如果有的话)没有任何区别。我总是使用详细数组方式;)但这只是偏好。我只是想指出,最初的问题是错误的括号位置,而不是数组和字符串。是的,我的代码是直接根据你在这里提出的建议编写的。我的错,我可能整晚都在敲我的头!
'order' => array('Post.distance' => 'ASC', 'limit' => 10)
'order' => array('Post.distance' => 'ASC'), 'limit' => 10