我有产品模型、商店模型和产品belongsTo商店模型,在商店模型中我有以下内容:
public function scopeWithDistance($query,$lat,$lng){
$q = $query;
if($lat != 0 && $lng != 0){
$raw = 'floor((floor(3959 * acos(cos(radians(:lat1)) * cos(radians(lat))
* cos(radians(lng) - radians(:lng))
+ sin(radians(:lng2)) * sin(radians(lat)))
)) * 1.609344) AS distance';
return $query->selectRaw($raw, [
'lat1' => $lat,
'lng' => $lng,
'lat2' => $lat,
]);
}
return $q;
}我可以很容易地获得Store加上计算出的距离:
App\Store::withDistance(20.6008362,-100.3966416)->get();在修修工。
但是,当我运行一个查询,试图通过我的产品模型获得Store::withDistance时,它不会返回距离字段:(
我的问题是:
$query = Product::whereHas('mm_product')
->with(['media', 'category', 'master_category', 'store.user.user_data', 'store.user.media', 'tag'])
->whereHas('store', function ($q) use ($state_id, $shop_id, $lat, $lng) {
if ($state_id && $shop_id == 0) {
$q->where(function ($q) use ($state_id, $lat, $lng) {
$q->whereNotNull('lat')->whereNotNull('lng')->where('state_id', $state_id)->withDistance($lat, $lng);
});
}
});请帮帮我:“(
编辑:我这样做,然后我想做一个orderBy和基于距离计算的结果。
发布于 2018-09-22 05:51:11
您必须添加您的距离搜索功能,在急切的加载,然后它将返回作为一个字段。当添加到whereHas时,它只过滤结果。所以更好的重用,你可以这样做
在Store模型中定义此函数(我已经更改了haversine代码)
public static function haversine($coordinates)
{
return '(6371 * acos(cos(radians(' . $coordinates['latitude'] . '))
* cos(radians(`lat`))
* cos(radians(`lng`)
- radians(' . $coordinates['longitude'] . '))
+ sin(radians(' . $coordinates['latitude'] . '))
* sin(radians(`latitude`))))';
}
public function scopeWithinDistance($query, $haversine, $radius = 5)
{
return $query->select('id', 'user_id')
->selectRaw("{$haversine} AS distance")
->whereRaw("{$haversine} < ?", [$radius])
->orderBy('distance');
}现在,在查询中使用它,如下
$haversine = Store::haversine(['latitude' => '20.6008362', 'longitude' => '-100.3966416']);
$query = Product::whereHas('mm_product')
->with(['media', 'category', 'master_category','store' => function($q) use($haversine){
$q->selectRaw("*, {$haversine} AS distance");
},'store.user.user_data', 'store.user.media', 'tag'])
->whereHas('store', function ($q) use ($state_id, $shop_id, $haversine) {
if ($state_id && $shop_id == 0) {
$q->where(function ($q) use ($state_id, $haversine) {
$q->whereNotNull('lat')->whereNotNull('lng')
->where('state_id', $state_id)
->withinDistance($haversine);
});
}
});它将给你以英里为单位的距离,如果你想要它以公里为单位,那么乘以1.60934。
https://stackoverflow.com/questions/52453445
复制相似问题