将 Haversine 公式与 Laravel eloquent 和多个 where 子句一起使用

Using Haversine formula with Laravel eloquent and multiple where clause

我需要从 table "properties" 中获取数据,我将 属性 的地址存储在经度和纬度以及 construction_type 等其他字段中,no_of_bedrooms、no_of_bathrooms。 现在我需要根据最近的位置过滤数据,并传递其他过滤器,如 construction_type、no_of_bedrooms、no_of_bathrooms.

我正在使用 Haversine 公式按给定位置获取最近的位置。 在传递其他过滤器时,我在编写 laravel eloqent 查询时遇到了复杂的问题。

$property = (new Property())->newQuery();
    if(\Request::get('Lat')!=null && \Request::get('Lng')!=null){
        $lat=\Request::get('Lat');
        $lng=\Request::get('Lng');
        $radius=200;
        $q="( 3959 * acos( cos( radians(' . $lat . ') ) * cos( radians( lat ) ) * cos( radians( lng ) - radians(' . $lng . ') ) + sin( radians(' . $lat .') ) * sin( radians(lat) ) ) )";
        $property->selectRaw("{$q} AS distance")->havingRaw("distance < ?", [$radius]);
    }

     if(\Request::get('construction_status')!=null){
         $property->where('construction_status', \Request::get('construction_status'));
     }
//other filters
return $property->get();

我希望结果是具有给定最近位置的属性以及其他过滤器

试着这样写你的查询

$property = \DB::table('seller_properties');
    if(\Request::get('construction_status')!="any"){
             $property->where('construction_status', \Request::get('construction_status'));
         }
    //other filters
    if(\Request::get('Lat')!="" && \Request::get('Lng')!=""){
      $lat=\Request::get('Lat');
    $lng=\Request::get('Lng');
      $haversineSQL='( 3959 * acos( cos( radians(' . $lat . ') ) * cos( radians( lat ) ) * cos( radians( lng ) - radians(' . $lng . ') ) + sin( radians(' . $lat .') ) * sin( radians(lat) ) ) )';
      // resolve haversine formula here
    $property->whereRaw($haversineSQL . '<= ?', [25]);
     }
    return $property->get();

注意: // dont initialize $property like this $property = (new Property())->newQuery();