将Mysql Nearby Query转换为Laravel API查询

时间:2018-04-12 15:10:26

标签: php mysql laravel api

我很好奇如何将此查询转换为Laravel查询。

这是我在phpmyadmin上尝试过的附近查询。

set @lat=37.034126;
set @lng=27.430235;

SELECT party_title, latitude, longitude, 111.045 * DEGREES(ACOS(COS(RADIANS(@lat))
 * COS(RADIANS(latitude))
 * COS(RADIANS(longitude) - RADIANS(@lng))
 + SIN(RADIANS(@lat))
 * SIN(RADIANS(latitude))))
AS distance_in_km
FROM parties
ORDER BY distance_in_km ASC
LIMIT 0,5

查询结果:

query results

我试过这样但它没有用。

   
 public function index(\Illuminate\Http\Request $request) {
        if($request->has('party_category')){
           $parties = Parties::where('party_category', $request->party_category)->get();//your new query here
        }
        else if($request->has('lat') && $request->has('long')){
            $parties = Parties::whereRaw("ACOS(SIN(RADIANS('latitude'))*SIN(RADIANS($request->lat))+COS(RADIANS('latitude'))*COS(RADIANS($request->lat))*COS(RADIANS('longitude')-RADIANS($request->long)))")->get();
        }else {
            $parties = Parties::all();
        }
        return Fractal::includes('places')->collection($parties,new PartyTransformer);
     }

我很好奇如何转换查询以及如何从查询中获取distance_in_km值,因为我想在api响应中显示。

2 个答案:

答案 0 :(得分:0)

在原始查询中应用select语句时,将selectRaw替换为whereRaw。

答案 1 :(得分:0)

我修复了问题,这里是代码我希望它会帮助某人:

    class PartiesController extends Controller
{
        public function index(\Illuminate\Http\Request $request) {
          if($request->has('lat') && $request->has('long')){
                $lat = $request->lat;
                $long = $request->long; 
            $parties=DB::select(DB::raw("SELECT *,111.045*DEGREES(ACOS(COS(RADIANS(':lat'))*COS(RADIANS(`latitude`))*COS(RADIANS(`longitude`) - RADIANS(':long'))+SIN(RADIANS(':lat'))*SIN(RADIANS(`latitude`)))) AS distance_in_km FROM parties ORDER BY distance_in_km asc LIMIT 0,5"), array(
                'lat' => $lat,
                'long' => $long
              ));
            $hidacik = Parties::hydrate($parties);
            return Fractal::includes('places')->collection($hidacik,new PartyTransformer);
             }
           else {
                $parties = Parties::all();
            }
       return Fractal::includes('places')->collection($parties,new PartyTransformer);
        }
}