DynamicAttributeTrait   A
last analyzed

Complexity

Total Complexity 3

Size/Duplication

Total Lines 32
Duplicated Lines 0 %

Importance

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

3 Methods

Rating   Name   Duplication   Size   Complexity  
A bootDynamicAttributeTrait() 0 4 1
A customsAttributes() 0 3 1
A scopeWithAttributeCodes() 0 7 1
1
<?php
2
3
namespace SimpleCMS\DynamicUnit\Traits;
4
5
use SimpleCMS\DynamicUnit\Models\CustomAttribute;
6
7
/**
8
 * 动态单元Trait
9
 *
10
 * @author Dennis Lui <[email protected]>
11
 *
12
 * 使用:
13
 * 
14
 *   use \SimpleCMS\DynamicUnit\Traits\DynamicAttributeTrait;
15
 *
16
 *
17
 * 请求查询方法:
18
 *
19
 *   $query->withAttributeCodes(array $codes);
20
 * 
21
 * @use \Illuminate\Database\Eloquent\Model
22
 * @use \Illuminate\Database\Eloquent\Concerns\HasRelationships
23
 *
24
 */
25
trait DynamicAttributeTrait
26
{
27
28
    public static function bootDynamicAttributeTrait()
29
    {
30
        static::deleting(function ($model) {
31
            $model->customsAttributes->each(fn(CustomAttribute $customsAttribute) => $customsAttribute->delete());
32
        });
33
    }
34
35
    /**
36
     * 动态单元
37
     * @return mixed
38
     */
39
    public function customsAttributes()
40
    {
41
        return $this->morphMany(CustomAttribute::class, 'model');
42
    }
43
44
    /**
45
     * 动态单元查询
46
     * @param mixed $query
47
     * @param array $codes
48
     * @return mixed
49
     */
50
    public function scopeWithAttributeCodes($query, array $codes)
51
    {
52
        return $query->whereHas('customsAttributes', function ($q) use ($codes) {
53
            $q->whereIn('dynamic_attribute_id', function ($subQuery) use ($codes) {
54
                $subQuery->select('id')
55
                    ->from('dynamic_attributes')
56
                    ->whereIn('code', $codes);
57
            });
58
        });
59
    }
60
61
}
62