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