1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Isswp101\Persimmon\Relationship; |
4
|
|
|
|
5
|
|
|
use Isswp101\Persimmon\Collection\ElasticsearchCollection; |
6
|
|
|
use Isswp101\Persimmon\ElasticsearchModel; |
7
|
|
|
use Isswp101\Persimmon\QueryBuilder\Filters\ParentFilter; |
8
|
|
|
use Isswp101\Persimmon\QueryBuilder\QueryBuilder; |
9
|
|
|
|
10
|
|
|
class HasManyRelationship |
11
|
|
|
{ |
12
|
|
|
/** |
13
|
|
|
* @var ElasticsearchModel |
14
|
|
|
*/ |
15
|
|
|
protected $parent; |
16
|
|
|
|
17
|
|
|
/** |
18
|
|
|
* @var ElasticsearchModel |
19
|
|
|
*/ |
20
|
|
|
protected $childClassName; |
21
|
|
|
|
22
|
2 |
|
public function __construct(ElasticsearchModel $parent, $childClassName) |
23
|
|
|
{ |
24
|
2 |
|
$this->parent = $parent; |
25
|
2 |
|
$this->childClassName = $childClassName; |
26
|
2 |
|
} |
27
|
|
|
|
28
|
|
|
/** |
29
|
|
|
* Find all children. |
30
|
|
|
* |
31
|
|
|
* @return ElasticsearchCollection|ElasticsearchModel[] |
32
|
|
|
*/ |
33
|
1 |
|
public function get() |
34
|
|
|
{ |
35
|
1 |
|
$child = $this->childClassName; |
36
|
1 |
|
$query = new QueryBuilder(); |
37
|
1 |
|
$query->filter(new ParentFilter($this->parent->getId())); |
38
|
1 |
|
$collection = $child::search($query); |
39
|
1 |
|
$collection->each(function (ElasticsearchModel $model) { |
40
|
1 |
|
$model->setParent($this->parent); |
41
|
1 |
|
}); |
42
|
1 |
|
return $collection; |
43
|
|
|
} |
44
|
|
|
|
45
|
|
|
/** |
46
|
|
|
* Find model by id. |
47
|
|
|
* |
48
|
|
|
* @param mixed $id |
49
|
|
|
* @return ElasticsearchModel|null |
50
|
|
|
*/ |
51
|
1 |
|
public function find($id) |
52
|
|
|
{ |
53
|
1 |
|
$child = $this->childClassName; |
54
|
1 |
|
$model = $child::findWithParentId($id, $this->parent->getId()); |
55
|
1 |
|
if ($model) { |
56
|
1 |
|
$model->setParent($this->parent); |
57
|
1 |
|
} |
58
|
1 |
|
return $model; |
59
|
|
|
} |
60
|
|
|
|
61
|
|
|
/** |
62
|
|
|
* Save children. |
63
|
|
|
* |
64
|
|
|
* @param ElasticsearchModel|ElasticsearchModel[] $child |
65
|
|
|
*/ |
66
|
1 |
|
public function save($child) |
67
|
|
|
{ |
68
|
|
|
/** @var ElasticsearchModel[] $children */ |
69
|
1 |
|
$children = !is_array($child) ? [$child] : $child; |
70
|
|
|
// @TODO: use bulk if count($children) > 1 |
71
|
1 |
|
foreach ($children as $child) { |
72
|
1 |
|
$child->setParent($this->parent); |
73
|
1 |
|
$child->save(); |
74
|
1 |
|
} |
75
|
1 |
|
} |
76
|
|
|
} |
77
|
|
|
|