1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Staudenmeir\EloquentJsonRelations\Relations; |
4
|
|
|
|
5
|
|
|
use Illuminate\Database\Eloquent\Collection; |
6
|
|
|
use Illuminate\Database\Eloquent\Model; |
7
|
|
|
use Illuminate\Database\Eloquent\Relations\Concerns\SupportsDefaultModels; |
8
|
|
|
use Illuminate\Database\Eloquent\Relations\HasOneOrMany; |
9
|
|
|
|
10
|
|
|
class HasOneJson extends HasManyJson |
11
|
|
|
{ |
12
|
|
|
use SupportsDefaultModels; |
13
|
|
|
|
14
|
|
|
/** @inheritDoc */ |
15
|
|
|
public function getResults() |
16
|
|
|
{ |
17
|
|
|
if (is_null($this->getParentKey())) { |
18
|
|
|
return $this->getDefaultFor($this->parent); |
19
|
|
|
} |
20
|
|
|
|
21
|
|
|
return $this->first() ?: $this->getDefaultFor($this->parent); |
22
|
|
|
} |
23
|
|
|
|
24
|
|
|
/** @inheritDoc */ |
25
|
|
|
public function initRelation(array $models, $relation) |
26
|
|
|
{ |
27
|
|
|
foreach ($models as $model) { |
28
|
|
|
$model->setRelation($relation, $this->getDefaultFor($model)); |
29
|
|
|
} |
30
|
|
|
|
31
|
|
|
return $models; |
32
|
|
|
} |
33
|
|
|
|
34
|
|
|
/** @inheritDoc */ |
35
|
|
|
public function match(array $models, Collection $results, $relation) |
36
|
|
|
{ |
37
|
|
|
return $this->matchOne($models, $results, $relation); |
38
|
|
|
} |
39
|
|
|
|
40
|
|
|
/** @inheritDoc */ |
41
|
|
|
public function matchOne(array $models, Collection $results, $relation) |
42
|
|
|
{ |
43
|
|
|
if ($this->hasCompositeKey()) { |
44
|
|
|
$this->matchWithCompositeKey($models, $results, $relation, 'one'); |
45
|
|
|
} else { |
46
|
|
|
HasOneOrMany::matchOneOrMany($models, $results, $relation, 'one'); |
47
|
|
|
} |
48
|
|
|
|
49
|
|
|
if ($this->key) { |
50
|
|
|
foreach ($models as $model) { |
51
|
|
|
$model->setRelation( |
52
|
|
|
$relation, |
53
|
|
|
$this->hydratePivotRelation( |
54
|
|
|
new Collection( |
55
|
|
|
array_filter([$model->$relation]) |
|
|
|
|
56
|
|
|
), |
57
|
|
|
$model, |
58
|
|
|
fn (Model $model) => $model->{$this->getPathName()} |
59
|
|
|
)->first() |
60
|
|
|
); |
61
|
|
|
} |
62
|
|
|
} |
63
|
|
|
|
64
|
|
|
return $models; |
65
|
|
|
} |
66
|
|
|
|
67
|
|
|
/** @inheritDoc */ |
68
|
|
|
public function newRelatedInstanceFor(Model $parent) |
|
|
|
|
69
|
|
|
{ |
70
|
|
|
return $this->related->newInstance(); |
71
|
|
|
} |
72
|
|
|
} |
73
|
|
|
|