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


Getting nearby data from lat/lng in CakePHP

我正在尝试使用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.latPost.lng。知道为什么它会创建错误的SQL吗?我的SQL技能是这样的,我不能发现错误,大概插件是OK的,有一些关于我的控制器动作。

最后,ASC后面有一个逗号,限制是反引号。当Cake得到它意想不到的参数时,它会对SQL查询做一些奇怪的事情。我怀疑你的问题在这里:

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

试题:

'order' => 'Post.distance ASC',
'limit' => 10

你的数组嵌套错了

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

应该是(注意右括号)

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