1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Isswp101\Persimmon\Relationship; |
4
|
|
|
|
5
|
|
|
use Illuminate\Database\Eloquent\ModelNotFoundException; |
6
|
|
|
use Isswp101\Persimmon\ElasticsearchModel; |
7
|
|
|
use ReflectionClass; |
8
|
|
|
|
9
|
|
|
class BelongsToRelationship |
10
|
|
|
{ |
11
|
|
|
/** |
12
|
|
|
* @var ElasticsearchModel |
13
|
|
|
*/ |
14
|
|
|
protected $child; |
15
|
|
|
|
16
|
|
|
/** |
17
|
|
|
* @var ElasticsearchModel |
18
|
|
|
*/ |
19
|
|
|
protected $parentClassName; |
20
|
|
|
|
21
|
|
|
function __construct(ElasticsearchModel $child, $parentClassName) |
|
|
|
|
22
|
|
|
{ |
23
|
|
|
$this->child = $child; |
24
|
|
|
$this->parentClassName = $parentClassName; |
25
|
|
|
} |
26
|
|
|
|
27
|
|
|
public function associate($parent) |
28
|
|
|
{ |
29
|
|
|
$this->child->setParent($parent); |
30
|
|
|
} |
31
|
|
|
|
32
|
|
|
/** |
33
|
|
|
* Return parent instance via inner_hits objects. |
34
|
|
|
* |
35
|
|
|
* @return ElasticsearchModel |
36
|
|
|
*/ |
37
|
|
|
public function get() |
38
|
|
|
{ |
39
|
|
|
$parent = $this->child->getParent(); |
40
|
|
|
|
41
|
|
|
if (!$parent) { |
42
|
|
|
$parentClassName = $this->parentClassName; |
43
|
|
|
$innerHit = $this->child->getInnerHits()->getParent($parentClassName::getType()); |
|
|
|
|
44
|
|
|
|
45
|
|
|
if ($innerHit) { |
46
|
|
|
$parent = new $parentClassName($innerHit); |
47
|
|
|
} elseif ($this->child->getParentId()) { |
48
|
|
|
$parent = $parentClassName::find($this->child->getParentId()); |
49
|
|
|
} |
50
|
|
|
|
51
|
|
|
if (!$parent) { |
52
|
|
|
$reflect = new ReflectionClass($parentClassName); |
53
|
|
|
throw new ModelNotFoundException(sprintf( |
54
|
|
|
'Model `%s` not found by id `%s`. Try to use inner_hits.', |
55
|
|
|
$reflect->getShortName(), $this->child->getParentId() |
56
|
|
|
)); |
57
|
|
|
} else { |
58
|
|
|
$this->child->setParent($parent); |
59
|
|
|
} |
60
|
|
|
} |
61
|
|
|
|
62
|
|
|
return $parent; |
63
|
|
|
} |
64
|
|
|
|
65
|
|
|
/** |
66
|
|
|
* Return parent instance via inner_hits objects. |
67
|
|
|
* |
68
|
|
|
* @return ElasticsearchModel |
69
|
|
|
*/ |
70
|
|
|
public function getOrFail() |
71
|
|
|
{ |
72
|
|
|
$model = $this->get(); |
73
|
|
|
|
74
|
|
|
if (is_null($model)) { |
75
|
|
|
throw new ModelNotFoundException(); |
76
|
|
|
} |
77
|
|
|
|
78
|
|
|
return $model; |
79
|
|
|
} |
80
|
|
|
} |
Adding explicit visibility (
private
,protected
, orpublic
) is generally recommend to communicate to other developers how, and from where this method is intended to be used.