|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Jidaikobo\Kontiki\Models\Traits; |
|
4
|
|
|
|
|
5
|
|
|
trait MetaDataTrait |
|
6
|
|
|
{ |
|
7
|
|
|
public function getAllMetaData(int $id): array |
|
8
|
|
|
{ |
|
9
|
|
|
$modelClass = static::class; |
|
10
|
|
|
$result = $this->db->table('meta_data') |
|
11
|
|
|
->where('target', $modelClass) |
|
12
|
|
|
->where('target_id', $id) |
|
13
|
|
|
->get() |
|
14
|
|
|
->map(fn($item) => [ |
|
15
|
|
|
'meta_key' => $item->meta_key, |
|
16
|
|
|
'meta_value' => json_decode($item->meta_value, true) |
|
17
|
|
|
]) |
|
18
|
|
|
->toArray(); |
|
19
|
|
|
|
|
20
|
|
|
$retvals = []; |
|
21
|
|
|
foreach ($result as $each) { |
|
22
|
|
|
$retvals[$each['meta_key']] = $each['meta_value']; |
|
23
|
|
|
} |
|
24
|
|
|
|
|
25
|
|
|
return $retvals; |
|
26
|
|
|
} |
|
27
|
|
|
|
|
28
|
|
|
public function getMetaData(int $id, string $key): mixed |
|
29
|
|
|
{ |
|
30
|
|
|
$modelClass = static::class; |
|
31
|
|
|
$result = $this->db->table('meta_data') |
|
32
|
|
|
->where('target', $modelClass) |
|
33
|
|
|
->where('target_id', $id) |
|
34
|
|
|
->where('meta_key', $key) |
|
35
|
|
|
->first(); |
|
36
|
|
|
|
|
37
|
|
|
if ($result) { |
|
38
|
|
|
$result = (array) $result; |
|
39
|
|
|
return json_decode($result['meta_value'], true); |
|
40
|
|
|
} |
|
41
|
|
|
|
|
42
|
|
|
return null; |
|
43
|
|
|
} |
|
44
|
|
|
|
|
45
|
|
|
public function createMetaData(int $id, string $key, mixed $value): void |
|
46
|
|
|
{ |
|
47
|
|
|
$modelClass = static::class; |
|
48
|
|
|
$data = [ |
|
49
|
|
|
'target' => $modelClass, |
|
50
|
|
|
'target_id' => $id, |
|
51
|
|
|
'meta_key' => $key, |
|
52
|
|
|
'meta_value' => json_encode($value), |
|
53
|
|
|
]; |
|
54
|
|
|
$this->db->table('meta_data')->insert($data); |
|
55
|
|
|
} |
|
56
|
|
|
|
|
57
|
|
|
public function updateMetaData(int $id, string $key, mixed $value): void |
|
58
|
|
|
{ |
|
59
|
|
|
$data = [ |
|
60
|
|
|
'meta_value' => json_encode($value), |
|
61
|
|
|
]; |
|
62
|
|
|
|
|
63
|
|
|
$modelClass = static::class; |
|
64
|
|
|
$this->db->table('meta_data') |
|
65
|
|
|
->where('target', $modelClass) |
|
66
|
|
|
->where('target_id', $id) |
|
67
|
|
|
->where('meta_key', $key) |
|
68
|
|
|
->update($data); |
|
69
|
|
|
} |
|
70
|
|
|
|
|
71
|
|
|
public function deleteMetaData(int $id, string $key): void |
|
72
|
|
|
{ |
|
73
|
|
|
$modelClass = static::class; |
|
74
|
|
|
$this->db->table('meta_data') |
|
75
|
|
|
->where('target', $modelClass) |
|
76
|
|
|
->where('target_id', $id) |
|
77
|
|
|
->where('meta_key', $key) |
|
78
|
|
|
->delete(); |
|
79
|
|
|
} |
|
80
|
|
|
} |
|
81
|
|
|
|