我正在开发一个Laravel应用程序,需要查找用户坐标范围内的所有产品。产品与用户之间是一对多的关系,因此用户可以拥有多个产品。我已经发现了一种名为haversine算法的方法可以计算两点之间的距离,但我似乎无法让它起作用。
以下是我的查询代码。
控制器
$latitude = 51.0258761;
$longitude = 4.4775362;
$radius = 20000;
$products = Product::with('user')
->selectRaw("*,
( 6371 * acos( cos( radians(" . $latitude . ") ) *
cos( radians(user.latitude) ) *
cos( radians(user.longitude) - radians(" . $longitude . ") ) +
sin( radians(" . $latitude . ") ) *
sin( radians(user.latitude) ) ) )
AS distance")
->having("distance", "<", $radius)
->orderBy("distance")
->get();
我已将半径设置为20000以进行测试,并且所有产品的距离都为5687,问题似乎是产品的纬度和经度存储在用户表中,但我不确定如何在我的查询中访问它们。我尝试了user.latitude和'user->latitude',但都没有起作用。产品模型
class Product extends Model
{
protected $fillable =
[
'soort',
'hoeveelheid',
'hoeveelheidSoort',
'prijsPerStuk',
'extra',
'foto',
'bio'
];
public function User()
{
return $this->belongsTo('App\User');
}
public $timestamps = true;
}
用户模型
use Illuminate\Auth\Authenticatable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Auth\Passwords\CanResetPassword;
use Illuminate\Foundation\Auth\Access\Authorizable;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\Access\Authorizable as AuthorizableContract;
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;
class User extends Model implements AuthenticatableContract,
AuthorizableContract,
CanResetPasswordContract
{
use Authenticatable, Authorizable, CanResetPassword;
protected $table = 'users';
protected $fillable =
[
'firstName',
'lastName',
'adres',
'profilepic',
'description',
'longitude',
'latitude',
'email',
'password'
];
protected $hidden = ['password', 'remember_token'];
public function product()
{
return $this->hasMany('App\Product');
}
}
3961
而不是6371
。 - Ohgodwhyselect()
中,我们将{$haversine} 别名为 distance
,这样你就可以select('distance')
。 - Ohgodwhy: Undefined function: 7 ERROR: operator does not exist: bigint = character varying LINE 6: ...) AS distance from "addresses" where "users"."id" = "address... ^ HINT: No operator matches the given name and argument type(s). You might need to add explicit type casts.
我已经研究了大约一个小时,但似乎无法解决它。从看起来的情况来看,我正在对字符串和小数进行数学运算。但是不知道该如何解决。我尝试将用户的纬度和经度转换为十进制数,但没有效果。 - Tim Bogdanov