gpt4 book ai didi

php - 在 Laravel 中计算坐标距离

转载 作者:可可西里 更新时间:2023-11-01 07:06:52 24 4
gpt4 key购买 nike

我的模型中有一个范围,它创建了一个别名,我需要在其上执行一个 where,我知道 MySql 不允许这样做。

Standard SQL doesn't allow you to refer to a column alias in a WHERE clause. This restriction is imposed because when the WHERE code is executed, the column value may not yet be determined.

但是,我想知道是否有可能的 laravel 解决方法?我的示波器创建了一个别名距离,我想检查该距离。

public static function scopeDistance($query, $lat, $long)
{
return $query->select(array('*',\DB::raw('( 3959 * acos( cos( radians(' . $lat . ') ) * cos( radians( latitude ) ) * cos( radians( longitude ) - radians(' . $long . ') ) + sin( radians(' . $lat .') ) * sin( radians(latitude) ) ) ) AS distance')));
}

在我的 Controller 中:

\App\Profile::distance($latitude, $longitude)->where('distance', '<', 50);

最佳答案

首先,不要忘记从函数调用中删除 static 关键字,Laravel 处理神奇的static-looking Profile::distance 打电话。

以下是解决同一问题的 2 个不同选项,无论哪种情况,您都将从 Controller 调用 \App\Profile::distance($latitude, $longitude, 50)

选项 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;
});
}

选项 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();
}

关于php - 在 Laravel 中计算坐标距离,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44293480/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com