laravel 具有:未找到列

laravel having: Column not found

我下面的代码是这样的:

$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]: Column not found: 1054 Unknown column 'distance' in 'having clause' (SQL: select count(*) as aggregate from dive_places having distance < 300)

有什么解决办法吗?

您需要重复距离定义,因为对于分页 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);
->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])