1 | <?php |
||
15 | trait InheritsRelationsFromParentModel |
||
16 | { |
||
17 | public $hasParent = true; |
||
18 | |||
19 | public static function bootHasParent() |
||
20 | { |
||
21 | static::creating(function ($model) { |
||
22 | if ($model->parentHasHasChildrenTrait()) { |
||
23 | $model->forceFill( |
||
24 | [$model->getInheritanceColumn() => $model->classToAlias(get_class($model))] |
||
25 | ); |
||
26 | } |
||
27 | }); |
||
28 | static::addGlobalScope(function ($query) { |
||
29 | $instance = new static(); |
||
30 | if ($instance->parentHasHasChildrenTrait()) { |
||
31 | $query->where($instance->getTable().'.'.$instance->getInheritanceColumn(), $instance->classToAlias(get_class($instance))); |
||
32 | } |
||
33 | }); |
||
34 | } |
||
35 | |||
36 | public function parentHasHasChildrenTrait() |
||
37 | { |
||
38 | return $this->hasChildren ?? false; |
||
39 | } |
||
40 | |||
41 | public function getTable() |
||
42 | { |
||
43 | if (!isset($this->table)) { |
||
44 | return str_replace('\\', '', Str::snake(Str::plural(class_basename($this->getParentClass())))); |
||
45 | } |
||
46 | |||
47 | return $this->table; |
||
48 | } |
||
49 | |||
50 | public function getForeignKey() |
||
54 | |||
55 | public function joiningTable($related, $instance = null) |
||
56 | { |
||
57 | $relatedClassName = method_exists((new $related()), 'getClassNameForRelationships') |
||
68 | |||
69 | public function getClassNameForRelationships() |
||
73 | |||
74 | public function getMorphClass() |
||
84 | |||
85 | protected function getParentClass() |
||
91 | } |
||
92 |
This check looks for methods that are used by a trait but not required by it.
To illustrate, let’s look at the following code example
The trait
Idable
provides a methodequalsId
that in turn relies on the methodgetId()
. If this method does not exist on a class mixing in this trait, the method will fail.Adding the
getId()
as an abstract method to the trait will make sure it is available.