laravel having: Column not found

扶醉桌前 提交于 2019-11-28 05:45:18

问题


my following code is like this:

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

without the "havingRaw" everything is good. After adding it, the following error came up:

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'distance' in 'having clause' (SQL: select count(*) as aggregate from dive_places having distance < 300)

Any solution?


回答1:


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

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




回答2:


You need to repeat distance definition because for pagination Laravel uses only count(*) for columns, so it should be:

$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);

You could also use bindings for the query, so better would be:

$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);


来源:https://stackoverflow.com/questions/33982661/laravel-having-column-not-found

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!