首先,不要忘记删除static
函数调用中的关键字,Laravel 处理神奇的静态的 Profile::distance
call.
以下是解决同一问题的 2 个不同选项,无论哪种情况,您都会致电\App\Profile::distance($latitude, $longitude, 50)
从您的控制器。
Option 1
您可以在内存中进行计算,而不用处理子查询。
public function scopeDistance($query, $lat, $long, $distance) {
return Profile::all()->filter(function ($profile) use ($lat, $long, $distance) {
$actual = 3959 * acos(
cos(deg2rad($lat)) * cos(deg2rad($profile->latitude))
* cos(deg2rad($profile->longitude) - deg2rad($long))
+ sin(deg2rad($lat)) * sin(deg2rad($profile->latitude))
);
return $distance < $actual;
});
}
Option 2
您可以执行 SQL 子查询,请确保以结束调用get()
:
public function scopeDistance($query, $lat, $long, $distance) {
return $query->having('distance', '<', $distance)
->select(DB::raw("*,
(3959 * ACOS(COS(RADIANS($lat))
* COS(RADIANS(latitude))
* COS(RADIANS($long) - RADIANS(longitude))
+ SIN(RADIANS($lat))
* SIN(RADIANS(latitude)))) AS distance")
)->orderBy('distance', 'asc')
->get();
}