RegionTrait   A
last analyzed

Complexity

Total Complexity 3

Size/Duplication

Total Lines 30
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 3
eloc 7
c 1
b 0
f 0
dl 0
loc 30
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A region() 0 3 1
A bootRegionTrait() 0 4 1
A scopeWithGeoDistance() 0 5 1
1
<?php
2
3
namespace SimpleCMS\Region\Traits;
4
5
use Illuminate\Support\Facades\DB;
6
use SimpleCMS\Region\Models\Region;
7
8
/**
9
 * 定位信息Trait
10
 *
11
 * @author Dennis Lui <[email protected]>
12
 *
13
 * 使用:
14
 * 
15
 *   use \SimpleCMS\Region\Traits\RegionTrait;
16
 *
17
 *
18
 * 请求查询方法:
19
 *
20
 *   $query->withGeoDistance(float $lat,float $lng,int $distance = 5000);
21
 * 
22
 * @use \Illuminate\Database\Eloquent\Model
23
 * @use \Illuminate\Database\Eloquent\Concerns\HasRelationships
24
 *
25
 */
26
trait RegionTrait
27
{
28
29
    public static function bootRegionTrait()
30
    {
31
        static::deleting(function ($model) {
32
            $model->region->each(fn(Region $region) => $region->delete());
33
        });
34
    }
35
36
    /**
37
     * 关联地区
38
     * @return mixed
39
     */
40
    public function region()
41
    {
42
        return $this->morphOne(Region::class, 'model');
43
    }
44
45
    /**
46
     * 按距离查询
47
     * @param mixed $query
48
     * @param array $codes
49
     * @return mixed
50
     */
51
    public function scopeWithGeoDistance($query, float $lat,float $lng,int $distance = 5000)
52
    {
53
        $raw = "ST_Distance_Sphere(geo,ST_GeomFromText('POINT($lng $lat)',4326))";
54
        return $query->whereHas('region', function ($q) use ($raw,$distance) {
55
            $q->select(DB::raw($raw.' as distance'))->where("distance <= $distance");
56
        });
57
    }
58
59
}
60