1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace UniSharp\Categorizable\Models; |
4
|
|
|
|
5
|
|
|
use Kalnoy\Nestedset\NodeTrait; |
6
|
|
|
use Illuminate\Database\Eloquent\Model; |
7
|
|
|
|
8
|
|
|
class Category extends Model |
9
|
|
|
{ |
10
|
|
|
use NodeTrait; |
11
|
|
|
|
12
|
|
|
protected $fillable = ['name', 'parent_id']; |
13
|
|
|
|
14
|
36 |
|
public static function boot() |
15
|
|
|
{ |
16
|
36 |
|
parent::boot(); |
17
|
|
|
static::deleting(function ($model) { |
18
|
2 |
|
collect(array_keys(config('categorizable.morphs')))->each(function ($relation) use ($model) { |
19
|
2 |
|
$model->{$relation}()->sync([]); |
20
|
2 |
|
}); |
21
|
36 |
|
}); |
22
|
36 |
|
} |
23
|
|
|
|
24
|
4 |
|
public function categorizables($class) |
25
|
|
|
{ |
26
|
4 |
|
return $this->morphedByMany($class, 'categorizable', 'categorizable', 'category_id'); |
27
|
|
|
} |
28
|
|
|
|
29
|
22 |
|
public function getRelationValue($key) |
30
|
|
|
{ |
31
|
22 |
|
if ($this->relationLoaded($key)) { |
32
|
22 |
|
return $this->relations[$key]; |
33
|
|
|
} |
34
|
|
|
|
35
|
|
|
if (array_key_exists($key, config('categorizable.morphs', []))) { |
36
|
|
|
$class = config('categorizable.morphs')[$key]; |
37
|
|
|
$relation = $this->categorizables($class); |
38
|
|
|
return tap($relation->getResults(), function ($results) use ($key) { |
39
|
|
|
$this->setRelation($key, $results); |
40
|
|
|
}); |
41
|
|
|
} |
42
|
|
|
|
43
|
|
|
return parent::getRelationValue($key); |
44
|
|
|
} |
45
|
|
|
|
46
|
|
|
|
47
|
36 |
|
public function __call($method, $arguments) |
48
|
|
|
{ |
49
|
36 |
|
if (array_key_exists($method, config('categorizable.morphs', []))) { |
50
|
4 |
|
$class = config('categorizable.morphs')[$method]; |
51
|
4 |
|
return $this->categorizables($class); |
52
|
|
|
} |
53
|
|
|
|
54
|
36 |
|
return parent::__call($method, $arguments); |
55
|
|
|
} |
56
|
|
|
} |
57
|
|
|
|