2014-02-10 93 views
0

我目前正在試圖建立一個原始查詢檢索在附近,這裏是我的嘗試laravel 4原始查詢錯誤

$places = DB::select('select * from b_details where(3959 * acos(cos(radians(37)) * cos(radians(lat = ?)) * cos(radians(lng = ?) - radians(-122)) + sin(radians(37)) * sin(radians(lat)))) 
as distance from b_details having distance < radius = ? order by distance LIMIT 0 , 20', array($lat, $lng, $radius)); 

我也試過:

$disctance_select = sprintf(
     "(3959 * acos(cos(radians(%s)) " . 
     " * cos(radians(lat)) " . 
     " * cos(radians(lng) - radians(%s)) " . 
     " + sin(radians(%s)) * sin(radians(lat)) " . 
     ") " . 
     ") " . 
     "AS distance", 
     $lat, 
     $lng, 
     $lat 
    ); 

    return DB::table('b_details') 
     ->having('distance', '<', $radius) 
     ->orderBy('distance', 'ASC') 
     ->get(array('*',$disctance_select)); 

這樣可以使產生錯誤:

SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax 

這是我試圖使用複製與laravel 4查詢:

SELECT id, (3959 * acos(cos(radians(37)) * cos(radians(lat)) * cos(radians(lng) - radians(-122)) + sin(radians(37)) * sin(radians(lat)))) AS distance FROM markers HAVING distance < 25 ORDER BY distance LIMIT 0 , 20; 

任何幫助表示讚賞,謝謝。

+0

請檢查下面Mr.Joe答案 –

回答

1

請檢查: 它確實工作:)

$result = Listing::select(
      DB::raw("*, 
          (6371 * acos(cos(radians(?)) * 
          cos(radians(lat)) 
          * cos(radians(lon) - radians(?) 
          ) + sin(radians(?)) * 
          sin(radians(lat))) 
         ) AS distance")) 
      ->having("distance", "<", $radius) 
      ->orderBy("distance") 
      ->setBindings([$lat, $lon, $lat]) 
      ->get(); 
0

您已完成select *後跟where後跟calculated column。您需要將distance計算列放在where子句之前。

爲什麼你不只是粘貼你試圖複製的查詢作爲第一個參數在Laravel DB:select?我很困惑你爲什麼要改變它。