laravel有:未找到列

时间:2015-11-29 12:17:30

标签: mysql laravel laravel-5.1 having laravel-pagination

我的以下代码是这样的:

$places = DivePlace::selectRaw("*,(st_distance_sphere( POINT(".$lon.",".$lat.") ,  point(lon, lat))/1000) as distance")
    ->havingRaw("distance < ".$radius)
    ->orderBy("distance")
    ->paginate(10);

没有“havingRaw”一切都很好。 添加后,出现以下错误:

  

SQLSTATE [42S22]:未找到列:1054未知列“距离”   'having clause'(SQL:从dive_places选择count(*)作为聚合   距离&lt; 300)

任何解决方案?

2 个答案:

答案 0 :(得分:2)

->where(DB::raw("(ST_Distance_Sphere(POINT(".$lon.",".$lat."), POINT(lon,lat))/1000)"), '<', 200)

而不是->havingRaw("(st_distance_sphere( POINT(?, ?) , point(lon, lat))/1000) < ?", [$lon, $lat, $radius])

答案 1 :(得分:0)

您需要重复距离定义,因为对于分页,Laravel仅对列使用count(*),因此它应该是:

$places = DivePlace::selectRaw("*,(st_distance_sphere( POINT(".$lon.",".$lat.") ,  point(lon, lat))/1000) as distance")
    ->havingRaw("(st_distance_sphere( POINT(".$lon.",".$lat.") ,  point(lon, lat))/1000) < ".$radius)
    ->orderBy("distance")
    ->paginate(10);

您也可以对查询使用绑定,因此最好是:

$places = DivePlace::selectRaw("*,(st_distance_sphere( POINT(?, ?) ,  point(lon, lat))/1000) as distance",[$lon, $lat])
    ->havingRaw("(st_distance_sphere( POINT(?, ?) ,  point(lon, lat))/1000) < ?", [$lon, $lat, $radius])
    ->orderBy("distance")
    ->paginate(10);