如何使用whereRaw将参数传递给查询中的方法?
我遇到了语法错误,出乎意料的'。''当试图添加“纬度”时和经度'列名是:
public function show($lon, $lat, $radio) {
$results = Viaje::where($otherStuff)
->whereRaw( 'radio + ' . $radio . ' <= ' . $this->getDistanceFromLatLonInKm($lat, $lon, . 'latitude, longitude)');
return response()->json($results);
}
如果我删除那个点,我最终将2个浮点数+ 2个字符串传递给我的方法而不是4个浮点数,所以我得到错误500.
public function show($lon, $lat, $radio)
{
$results = Viaje::where($otherStuff)->whereRaw( 'radio + ' . $radio . ' <= ' . $this->getDistanceFromLatLonInKm($lat, $lon, 'latitude', 'longitude'));
return response()->json($results);
}
编辑:
&#39; radio&#39;,&#39;经度&#39;和&#39;纬度&#39;是包含浮点值的列名。
public function getDistanceFromLatLonInKm($lat1,$lon1,$lat2,$lon2) {
$R = 6371; // Radius of the earth in km
$dLat = deg2rad($lat2-$lat1);
$dLon = deg2rad($lon2-$lon1);
$a = sin($dLat/2) * sin($dLat/2) + cos(deg2rad($lat1)) * cos(deg2rad($lat2))
+ sin($dLon/2) * sin($dLon/2);
$c = 2 * atan2(sqrt($a), sqrt(1-$a));
$d = R * c; // Distance in km
return $d;
}
答案 0 :(得分:0)
尝试一下:
public function show($lon, $lat, $radio)
{
$results = Viaje::where($otherStuff)->selectRaw('*,(
6371 * acos (
cos ( radians($lat) )
* cos( radians( latitude ) )
* cos( radians( longitude ) - radians($lon) )
+ sin ( radians($lat) )
* sin( radians( latitude ) )
)
)AS distance')
->whereRaw(radio + ' . $radio . ' <= distance')
->get();
return response()->json($results);
}
答案 1 :(得分:0)
我假设无线电是表名,其中有这个纬度和经度列,如果不是那么用表名替换radio而不是radio.longitude和radio.latitude到tablename.latitude和tablename.longitude
public function show($lon, $lat, $radio) {
$results = Viaje::where($otherStuff)
->whereRaw( 'radio + ' . $radio . ' <= ' .$this->getDistanceFromLatLonInKm($lat, $lon,radio.latitude, radio.longitude));
return response()->json($results);
}
答案 2 :(得分:0)
你可以尝试一下,看看它产生了什么结果 公共功能节目($ lon,$ lat,$ radio){
$results = Viaje::where($otherStuff)->select('fields','radio + '. $radio .'as total_radio')
->whereRaw('total_radio <='. function($q) use ($lat,$lot,$this) {
return $this->getDistanceFromLatLonInKm($lat, $lon,$q->select('lattitude'), $q->select('longitude'));
});
return response()->json($results);
}