Laravel 查询附近的数据

Laravel 查询附近的数据

数据结构

app\Models\School.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class School extends Model
{
protected $table = 'school';

public function getDistanceAttribute($value)
{
$value = sprintf('%.2f', $value);
return $value > 1 ? $value . 'km' : ($value * 1000) . 'm';
}
}

app\Http\Controllers\SearchController.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
<?php

namespace App\Http\Controllers;

use App\Models\School;
use Illuminate\Support\Facades\Validator;
use Illuminate\Http\Request;

class SearchController extends Controller
{
public function index(Request $request)
{
$input = $request->only(['lat', 'lng']);

$validator = Validator::make($input, [
'lat' => [
'required',
'regex:/^[\-\+]?(0?\d{1,2}\.\d{1,6}|1[0-7]?\d{1}\.\d{1,6}|180\.0{1,6})$/'
],
'lng' => [
'required',
'regex:/^[\-\+]?([0-8]?\d{1}\.\d{1,6}|90\.0{1,6})$/'
],
]);

// $validator->setAttributeNames([
// 'lat' => '经度',
// 'lng' => '纬度',
// ]);

if($validator->fails()) {
return $validator->errors()->first();
}

// 附近 n 公里
$distance = $request->query('distance', 5);

$data = School::select('*')
->selectRaw('( 6371 * acos( cos( radians(' . $input['lat'] . ') ) * cos( radians( lat ) ) * cos( radians( lng ) - radians(' . $input['lng'] . ') ) + sin( radians(' . $input['lat'] .') ) * sin( radians(lat) ) ) ) AS distance')
->havingRaw('distance < ' . $distance)
->orderBy('distance')
->get();

return response()->json([
'data' => $data,
]);
}
}

routes\web.php

1
Route::get('/', 'SearchController@index');

往上