dongwei2610 2016-08-18 22:23
浏览 263

使用whereRaw将参数传递给查询中的方法

How can I pass parameters to a method in my query using whereRaw?

I've got 'syntax error, unexpected '.'' when trying to add 'latitude' and 'longitude' which are column names:

public function show($lon, $lat, $radio) {
  $results = Viaje::where($otherStuff)
                  ->whereRaw( 'radio + ' . $radio . ' <= ' . $this->getDistanceFromLatLonInKm($lat, $lon, . 'latitude, longitude)');
  return response()->json($results);
}

If I delete that dot, I end up passing 2 floats + 2 strings to my method instead the 4 floats required, so I get error 500.

public function show($lon, $lat, $radio) 
{   
    $results = Viaje::where($otherStuff)->whereRaw( 'radio + ' . $radio . ' <= ' . $this->getDistanceFromLatLonInKm($lat, $lon, 'latitude', 'longitude'));   
    return response()->json($results); 
}

Edit:

'radio', 'longitude' and 'latitude' are column names containing a float value.

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;
}
  • 写回答

3条回答 默认 最新

  • doutuan9357 2016-08-19 13:59
    关注

    Give this a try:

    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); 
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 jupyterthemes 设置完毕后没有效果
  • ¥15 matlab图像高斯低通滤波
  • ¥15 针对曲面部件的制孔路径规划,大家有什么思路吗
  • ¥15 钢筋实图交点识别,机器视觉代码
  • ¥15 如何在Linux系统中,但是在window系统上idea里面可以正常运行?(相关搜索:jar包)
  • ¥50 400g qsfp 光模块iphy方案
  • ¥15 两块ADC0804用proteus仿真时,出现异常
  • ¥15 关于风控系统,如何去选择
  • ¥15 这款软件是什么?需要能满足我的需求
  • ¥15 SpringSecurityOauth2登陆前后request不一致