【问题标题】:Using Haversine formula with Laravel eloquent and multiple where clause将 Haversine 公式与 Laravel eloquent 和多个 where 子句一起使用
【发布时间】:2019-07-18 03:24:11
【问题描述】:

我需要从表“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();

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

【问题讨论】:

  • 你有什么问题?您的任何其他过滤器是否致电select()
  • 我在使用 $property = (new Property())-&gt;newQuery(); 编写原始 sql 查询时遇到问题

标签: laravel eloquent haversine


【解决方案1】:

试着这样写你的查询

$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())-&gt;newQuery();

【讨论】:

  • 谢谢你..你让我开心
猜你喜欢
  • 2019-11-27
  • 1970-01-01
  • 1970-01-01
  • 2020-08-03
  • 1970-01-01
  • 2013-10-19
  • 2015-08-06
相关资源
最近更新 更多