CakePHP在WHERE子句中放置函数名称周围的引号

时间:2009-10-16 17:08:52

标签: postgresql cakephp geolocation

我正在使用PostgreSQL中的earthdistance模块中的各种函数,其中一个是ll_to_earth。给定纬度/经度组合,我试图通过CakePHP 1.2.5 Stable从我的数据库中检索最近的点。

// set dummy data
$latitude  =  30.4393696;
$longitude = -97.6200043;

// create a simple bounding box in the WHERE conditions, sort the points by location, and retrieve the nearest point
$location = $this->Location->find('first', array(
    'fields' => array(
        'id',
        'coords',
        "earth_distance(coords, ll_to_earth($latitude, $longitude)) AS distance",
    ),
    'conditions' => array(
        'coords >=' => 'll_to_earth(' . ($latitude - 0.5) . ', ' . ($longitude - 0.5) . ')',
        'coords <=' => 'll_to_earth(' . ($latitude + 0.5) . ', ' . ($longitude + 0.5) . ')',
    ),
    'order' => array('distance ASC'),
));

SQL输出(为便于阅读而格式化)最终看起来像这样:

SELECT
  "Location"."id" AS "Location__id",
  "Location"."coords" AS "Location__coords",
  earth_distance(coords, ll_to_earth(30.4393696, -97.6200043)) AS distance FROM "locations" AS "Location"
WHERE
  "coords" >= 'll_to_earth(29.9393696, -97.1200043)' AND
  "coords" <= 'll_to_earth(30.9393696, -96.1200043)'
ORDER BY
  "distance" ASC
LIMIT 1

您可以看到我的问题所在:CakePHP引用了我的查找条件,包括函数名ll_to_earth。我是否只需要通过Model的query方法手动查询,或者有没有办法告诉Cake ll_to_earth是一个DB函数而不引用它?

1 个答案:

答案 0 :(得分:3)

你应该能够这样做:

$location = $this->Location->find('first', array(
    'fields' => array(
        'id',
        'coords',
        "earth_distance(coords, ll_to_earth($latitude, $longitude)) AS distance",
    ),
    'conditions' => array(
        'coords >= ll_to_earth(' . ($latitude - 0.5) . ', ' . ($longitude - 0.5) . ') 
        and coords <= ll_to_earth(' . ($latitude + 0.5) . ', ' . ($longitude + 0.5) . ')'),
    'order' => array('distance ASC'),
));

但这也会绕过Cake对输入所做的所有消毒,所以你必须自己照顾它。

相关问题