How to bind parameters to a raw DB query in Laravel that's used on a model?

后端 未结 6 564
迷失自我
迷失自我 2020-11-29 01:41

Re,

I have the following query:

$property = 
    Property::select(
        DB::raw(\"title, lat, lng, ( 
            3959 * acos( 
                co         


        
6条回答
  •  星月不相逢
    2020-11-29 02:18

    I ported the nearby search from Doctrine v1 to Laravel, check it out here.

    Just add the Geographical trait to the model then you can do:

    $model->newDistanceQuery($request->query('lat'), $request->query('lon'))->orderBy('miles', 'asc')->get();
    

    It works by using selectRaw with bindings like this:

    $sql = "((ACOS(SIN(? * PI() / 180) * SIN(" . $latName . " * PI() / 180) + COS(? * PI() / 180) * COS(" . $latName . " * PI() / 180) * COS((? - " . $lonName . ") * PI() / 180)) * 180 / PI()) * 60 * ?) as " . $unit;
    if($kilometers){
        $query->selectRaw($sql, [$lat, $lat, $lon, 1.1515 * 1.609344]);
    }
    else{
        // miles
        $query->selectRaw($sql, [$lat, $lat, $lon, 1.1515]);
    }
    

提交回复
热议问题