【问题标题】:Getting nearby data from lat/lng in CakePHP在 CakePHP 中从 lat/lng 获取附近的数据
【发布时间】:2014-08-11 23:31:40
【问题描述】:

我正在尝试使用 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 技能如此之高,我无法发现错误,大概是插件没问题,而且我的控制器操作有些问题。

【问题讨论】:

  • 看起来它现在工作得很好:) PS:在较新的版本中,您可以使用 load() 而不是 attach()。后者已弃用。

标签: php sql cakephp cakephp-2.4


【解决方案1】:

最后,ASC 后面有一个逗号,limit 用反引号表示。当Cake 得到它不期望的参数时,它会用SQL 查询做一些奇怪的事情。我怀疑你的问题是这样的:

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

试试:

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

【讨论】:

  • 订单的数组版本工作得很好 - 如果右括号是它们所属的地方.. ;) 请参阅我的答案。
  • 嗨,马克。该数组是不必要的,因为只传递了一个订单标准,这就是我删除它的原因。除了加长代码(如果存在)之外,它没有任何区别。
  • 我总是使用详细的数组方式;)但这只是偏好。我只是想指出最初的问题是错误的括号放置,而不是数组与字符串。
【解决方案2】:

你基本上错误地嵌套了你的数组

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

应该是(注意右括号)

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

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-01-25
  • 2016-05-10
  • 1970-01-01
  • 2017-04-13
  • 2022-01-02
  • 1970-01-01
  • 2015-05-08
相关资源
最近更新 更多