1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace A17\Twill\Models\Behaviors; |
4
|
|
|
|
5
|
|
|
use A17\Twill\Models\RelatedItem; |
6
|
|
|
use Illuminate\Database\Eloquent\Relations\MorphMany; |
7
|
|
|
use Illuminate\Support\Arr; |
8
|
|
|
use Illuminate\Support\Collection; |
9
|
|
|
|
10
|
|
|
trait HasRelated |
11
|
|
|
{ |
12
|
|
|
protected $relatedCache; |
13
|
|
|
|
14
|
|
|
public function relatedItems() |
15
|
|
|
{ |
16
|
|
|
return $this->morphMany(RelatedItem::class, 'subject')->orderBy('position'); |
|
|
|
|
17
|
|
|
} |
18
|
|
|
|
19
|
|
|
public function getRelated($browser_name) |
20
|
|
|
{ |
21
|
|
|
if (!isset($this->relatedCache[$browser_name]) || $this->relatedCache[$browser_name] === null) { |
22
|
|
|
$this->loadRelated($browser_name); |
23
|
|
|
} |
24
|
|
|
|
25
|
|
|
return $this->relatedCache[$browser_name]; |
26
|
|
|
} |
27
|
|
|
|
28
|
|
|
public function loadRelated($browser_name) |
29
|
|
|
{ |
30
|
|
|
if (!isset($this->relatedItems)) { |
|
|
|
|
31
|
|
|
$this->load('relatedItems'); |
|
|
|
|
32
|
|
|
} |
33
|
|
|
|
34
|
|
|
return $this->relatedCache[$browser_name] = $this->relatedItems |
35
|
|
|
->where('browser_name', $browser_name) |
36
|
|
|
->map(function ($item) { |
37
|
|
|
return $item->related; |
38
|
|
|
}); |
39
|
|
|
} |
40
|
|
|
|
41
|
|
|
public function saveRelated($items, $browser_name) |
42
|
|
|
{ |
43
|
|
|
RelatedItem::where([ |
44
|
|
|
'browser_name' => $browser_name, |
45
|
|
|
'subject_id' => $this->getKey(), |
|
|
|
|
46
|
|
|
'subject_type' => $this->getMorphClass(), |
|
|
|
|
47
|
|
|
])->delete(); |
48
|
|
|
|
49
|
|
|
$position = 1; |
50
|
|
|
|
51
|
|
|
Collection::make($items)->map(function ($item) { |
52
|
|
|
return Arr::only($item, ['endpointType', 'id']); |
53
|
|
|
})->each(function ($values) use ($browser_name, &$position) { |
54
|
|
|
RelatedItem::create([ |
55
|
|
|
'subject_id' => $this->getKey(), |
56
|
|
|
'subject_type' => $this->getMorphClass(), |
57
|
|
|
'related_id' => $values['id'], |
58
|
|
|
'related_type' => $values['endpointType'], |
59
|
|
|
'browser_name' => $browser_name, |
60
|
|
|
'position' => $position, |
61
|
|
|
]); |
62
|
|
|
$position++; |
63
|
|
|
}); |
64
|
|
|
} |
65
|
|
|
} |
66
|
|
|
|