如何将 mysql 距离查询转换为 Laravel Eloquent 查询? - (带有纬度、经度和半径参数)

How to convert mysql distance query to Laravel Eloquent query? - (with Latitude, Longitude and Radius param)

我有一个 mysql 查询可以获取组织的最近位置。我想将其转换为 Laravel eloquent 查询,以便我可以获得组织模型的属性功能。可能吗?这是我的代码:

public function getNearesOraganization(Request $request)
    {

        $mi = 10;
        $centerLat = $request->lat;
        $centerLng = $request->lng;
        // $orgs = Organization::all();
        // foreach ($orgs as $key => $value) {
        //     $value->distance = $this->distance(floatval($centerLat), floatval($centerLng), floatval($value->lat), floatval($value->lng));
        //     dump($value->distance);
        // }

        $orgs = \DB::select(
            \DB::raw(

                "SELECT id,
                        org_name,
                        org_street,
                        org_cityprov,
                        org_state,
                        org_zipcode,
                        org_lat,
                        org_lng,
                        ( 3958.8  *
                            acos(
                                    cos( radians($centerLat) ) *
                                    cos( radians( org_lat ) ) *
                                    cos( radians( org_lng ) - radians($centerLng) ) +
                                    sin( radians($centerLat)) *
                                    sin( radians( org_lat ) )
                                )
                        )
                        AS distance
                FROM organizations
                HAVING distance < $mi
                ORDER BY distance ASC"
            )
        );

        foreach ($orgs as $key => $value) {
            $value->f_distance = number_format($value->distance, 2);
        }

        return response()->json($orgs, 200);
    }

一种方法是使用

https://github.com/malhal/Laravel-Geographical 这个库

那么您的代码将是

public function getNearesOraganization(Request $request)
{
    $query = Model::geofence($request->lat, $request->lng, 0, 10);
    $orgs = $query->get();

    return response()->json($orgs, 200);
}

我使用 Laravel 模型范围

对其进行了编码
public function scopeNearestInMiles($query, $mi, $centerLat, $centerLng)
    {
        return $query
            ->select(\DB::raw("*,(3958.8  *
                                acos(
                                        cos( radians(" . $centerLat . ") ) *
                                        cos( radians( org_lat ) ) *
                                        cos( radians( org_lng ) - radians(" . $centerLng . ") ) +
                                        sin( radians(" . $centerLat . ")) *
                                        sin( radians( org_lat ) )
                                    )
                            )
                            AS distance"))
            ->having('distance', '<', $mi)
            ->orderBy('distance');
    }

在控制器中

$orgs = Organization::nearestInMiles($mi,$centerLat,$centerLng)->get();