2017-02-14 95 views
0

我試圖顯示距離爲我的搜索結果添加距離查詢結果

代碼和查詢

$query = DB::select(DB::raw('SELECT id, (3959 * acos(cos(radians(' . $lat . ')) * cos(radians(latitude)) * cos(radians(longitude) - radians(' . $lng . ')) + sin(radians(' . $lat .')) * sin(radians(latitude)))) AS distance FROM listings HAVING distance < ' . $distance . ' ORDER BY distance')); 
     foreach($query as $q) 
     { 
      array_push($ids, $q->id); 

     } 
     $placeholders = implode(',',array_fill(0, count($ids), '?')); 
     $listings = Listing::whereIn('id', $ids)->orderByRaw("field(id,{$placeholders})", $ids)->paginate(10); 

$查詢包含距離。

如何在列表結果中添加距離?

回答

0

將距離選擇查詢也附加到雄辯查詢。

使用以下方法;

Listing::select([ 
    "*", 
    "(3959 * acos(cos(radians(' . $lat . ')) * cos(radians(latitude)) * cos(radians(longitude) - radians(' . $lng . ')) + sin(radians(' . $lat .')) * sin(radians(latitude)))) AS distance" 
])...... 

此外,爲什麼不使用第一個查詢的結果,您不需要執行兩次相同的查詢。

+0

$房源=上市::選擇([ \t \t \t 「*」, \t \t \t「(3959個* ACOS(COS(弧度('。$ lat。'))* cos(弧度(緯度))* cos(弧度(經度) - 弧度('。$ lng。'))+ sin(弧度('。$ lat。'))* sin(radians(latitude))))AS distance「 \t \t \t] - > having('distance','<',$ distance) - > orderBy('distan CE「) - >獲得(); 我收到錯誤 –

+0

SQLSTATE [42000]:語法錯誤或訪問衝突:1064您的SQL語法錯誤;檢查與您的MariaDB服務器版本相對應的手冊,以找到正確的語法,以便在'距離'''''''''''''''距離'<?在第1行用'distance' asc'命令(SQL:select *,'('as'from'listings'''distance' <5 order by'distance' asc) –

+0

指定帶星號「列表的表名」。* 「 –

0

如果你想獲得導致任何特定的距離:

$radius = 15; 
Listing::select(
     DB::raw("*, (6371 * acos(cos(radians('".$lat."')) * cos(radians(latitude)) * cos(radians(longitude) - radians('".$lon."')) + sin(radians('".$lat."')) * sin(radians(latitude)))) AS **distance**" 
      ) 
     ) 
     ->having("distance", "<", $radius) 
     ->orderBy("distance") 
     ->get();