Test Setup Failed
Push — master ( ad0913...368932 )
by Dennis
14:58
created

RegionTrait::region()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 1
c 1
b 0
f 0
dl 0
loc 3
rs 10
cc 1
nc 1
nop 0
1
<?php
2
3
namespace SimpleCMS\Region\Traits;
4
5
use SimpleCMS\Region\Models\Region;
6
7
/**
8
 * 定位信息Trait
9
 *
10
 * @author Dennis Lui <[email protected]>
11
 *
12
 * 使用:
13
 * 
14
 *   use \SimpleCMS\Region\Traits\RegionTrait;
15
 *
16
 *
17
 * 请求查询方法:
18
 *
19
 *   $query->withGeoDistance(float $lat,float $lng,int $distance = 5000);
20
 * 
21
 * @use \Illuminate\Database\Eloquent\Model
22
 * @use \Illuminate\Database\Eloquent\Concerns\HasRelationships
23
 *
24
 */
25
trait RegionTrait
26
{
27
28
    public static function bootRegionTrait()
29
    {
30
        static::deleting(function ($model) {
31
            $model->region->each(fn(Region $region) => $region->delete());
32
        });
33
    }
34
35
    /**
36
     * 关联地区
37
     * @return mixed
38
     */
39
    public function region()
40
    {
41
        return $this->morphOne(Region::class, 'model');
1 ignored issue
show
Bug introduced by
It seems like morphOne() must be provided by classes using this trait. How about adding it as abstract method to this trait? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

41
        return $this->/** @scrutinizer ignore-call */ morphOne(Region::class, 'model');
Loading history...
42
    }
43
44
    /**
45
     * 按距离查询
46
     * @param mixed $query
47
     * @param array $codes
48
     * @return mixed
49
     */
50
    public function scopeWithGeoDistance($query, float $lat,float $lng,int $distance = 5000)
51
    {
52
        $raw = "ST_Distance_Sphere(geo,ST_GeomFromText('POINT($lng $lat)',4326))";
53
        return $query->whereHas('region', function ($q) use ($raw,$distance) {
54
            $q->select(DB::raw($raw.' as distance'))->where("distance <= $distance");
0 ignored issues
show
Bug introduced by
The type SimpleCMS\Region\Traits\DB was not found. Did you mean DB? If so, make sure to prefix the type with \.
Loading history...
55
        });
56
    }
57
58
}
59