我希望通过到点的位置(纬度/经度)的距离对查询中的结果进行排序。
我正在使用Doctrine2和Symfony2.8,这是我的查询:
public function findByPoint(Point $point)
{
$sql = sprintf(
'(6371 * acos(cos(radians(%s)) * cos(radians(X(s.point))) * cos(radians(Y(s.point)) -
radians(%s)) + sin(radians(%s)) * sin(radians(X(s.point)))))', $point->getLatitude(), $point->getLongitude(), $point->getLatitude());
$qb = $this->createQueryBuilder('s');
return $qb
->orderBy($sql, 'ASC')
->setMaxResults(5)
->getQuery()
->getResult();
}
但是这不起作用,它会引发异常[Syntax Error] line 0, col 60: Error: Expected end of string, got '6371'
。
有没有办法将自定义SQL注入此方法或以DQL方式创建自定义顺序?
答案 0 :(得分:2)
您需要将自定义函数与Doctrine2一起用于地理坐标。
尝试使用此自定义DistanceFunction
:https://gist.github.com/Koc/3016704
或此捆绑包:https://github.com/craue/CraueGeoBundle
以下是Doctrine函数提供的所有内容的列表:http://docs.doctrine-project.org/en/latest/reference/dql-doctrine-query-language.html#dql-functions
IDENTITY(single_association_path_expression [, fieldMapping]) - Retrieve the foreign key column of association of the owning side
ABS(arithmetic_expression)
CONCAT(str1, str2)
CURRENT_DATE() - Return the current date
CURRENT_TIME() - Returns the current time
CURRENT_TIMESTAMP() - Returns a timestamp of the current date and time.
LENGTH(str) - Returns the length of the given string
LOCATE(needle, haystack [, offset]) - Locate the first occurrence of the substring in the string.
LOWER(str) - returns the string lowercased.
MOD(a, b) - Return a MOD b.
SIZE(collection) - Return the number of elements in the specified collection
SQRT(q) - Return the square-root of q.
SUBSTRING(str, start [, length]) - Return substring of given string.
TRIM([LEADING | TRAILING | BOTH] [‘trchar’ FROM] str) - Trim the string by the given trim char, defaults to whitespaces.
UPPER(str) - Return the upper-case of the given string.
DATE_ADD(date, days, unit) - Add the number of days to a given date. (Supported units are DAY, MONTH)
DATE_SUB(date, days, unit) - Substract the number of days from a given date. (Supported units are DAY, MONTH)
DATE_DIFF(date1, date2) - Calculate the difference in days between date1-date2.
默认情况下不支持 acos, cos, radians
(没有自定义扩展名)。