1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Thinktomorrow\Chief\Relations; |
4
|
|
|
|
5
|
|
|
use Illuminate\Database\Eloquent\Collection; |
6
|
|
|
|
7
|
|
|
trait ActingAsChild |
8
|
|
|
{ |
9
|
|
|
protected $loadedParentRelations; |
10
|
|
|
|
11
|
7 |
|
public function parents(): Collection |
12
|
|
|
{ |
13
|
7 |
|
if ($this->areParentRelationsLoaded()) { |
14
|
5 |
|
return $this->loadedParentRelations; |
15
|
|
|
} |
16
|
|
|
|
17
|
7 |
|
return $this->loadedParentRelations = Relation::parents($this->getMorphClass(), $this->getKey()); |
|
|
|
|
18
|
|
|
} |
19
|
|
|
|
20
|
4 |
|
public function acceptParent(ActsAsParent $parent, array $attributes = []) |
21
|
|
|
{ |
22
|
|
|
// Reset cached relation |
23
|
4 |
|
$this->loadedParentRelations = null; |
24
|
|
|
|
25
|
4 |
|
$this->attachParent($parent->getMorphClass(), $parent->getKey(), $attributes); |
|
|
|
|
26
|
4 |
|
} |
27
|
|
|
|
28
|
1 |
|
public function rejectParent(ActsAsParent $parent) |
29
|
|
|
{ |
30
|
|
|
// Reset cached relation |
31
|
1 |
|
$this->loadedParentRelations = null; |
32
|
|
|
|
33
|
1 |
|
$this->detachParent($parent->getMorphClass(), $parent->getKey()); |
34
|
1 |
|
} |
35
|
|
|
|
36
|
1 |
|
public function relationWithParent(ActsAsParent $parent): Relation |
37
|
|
|
{ |
38
|
1 |
|
return Relation::query() |
|
|
|
|
39
|
1 |
|
->where('parent_type', $parent->getMorphClass()) |
40
|
1 |
|
->where('parent_id', $parent->getKey()) |
41
|
1 |
|
->where('child_type', $this->getMorphClass()) |
42
|
1 |
|
->where('child_id', $this->getKey()) |
43
|
1 |
|
->first(); |
44
|
|
|
} |
45
|
|
|
|
46
|
4 |
|
public function detachAllParentRelations() |
47
|
|
|
{ |
48
|
4 |
|
Relation::deleteAllParentRelationsOf($this->getMorphClass(), $this->getKey()); |
49
|
4 |
|
} |
50
|
4 |
|
|
51
|
4 |
|
private function attachParent($parent_type, $parent_id, array $attributes = []) |
52
|
4 |
|
{ |
53
|
4 |
|
Relation::firstOrCreate([ |
54
|
4 |
|
'parent_type' => $parent_type, |
55
|
|
|
'parent_id' => $parent_id, |
56
|
1 |
|
'child_type' => $this->getMorphClass(), |
57
|
|
|
'child_id' => $this->getKey(), |
58
|
1 |
|
], $attributes); |
59
|
1 |
|
} |
60
|
1 |
|
|
61
|
1 |
|
private function detachParent($parent_type, $parent_id) |
62
|
1 |
|
{ |
63
|
1 |
|
Relation::query() |
64
|
1 |
|
->where('child_type', $this->getMorphClass()) |
65
|
|
|
->where('child_id', $this->getKey()) |
66
|
7 |
|
->where('parent_type', $parent_type) |
67
|
|
|
->where('parent_id', $parent_id) |
68
|
7 |
|
->delete(); |
69
|
|
|
} |
70
|
|
|
|
71
|
|
|
private function areParentRelationsLoaded(): bool |
72
|
|
|
{ |
73
|
|
|
return !is_null($this->loadedParentRelations); |
74
|
|
|
} |
75
|
|
|
} |
76
|
|
|
|