1 | <?php |
||
2 | |||
3 | namespace Volosyuk\SimpleEloquent\Relations; |
||
4 | |||
5 | use Illuminate\Database\Eloquent\Relations\BelongsTo as BaseBelongsTo; |
||
6 | use Illuminate\Support\Collection; |
||
7 | use Volosyuk\SimpleEloquent\ModelAccessor; |
||
8 | |||
9 | /** |
||
10 | * Class BelongsToWithSimple |
||
11 | * @package Volosyuk\SimpleEloquent |
||
12 | */ |
||
13 | class BelongsTo extends BaseBelongsTo |
||
14 | { |
||
15 | use Relation; |
||
16 | |||
17 | /** |
||
18 | * Match the eagerly loaded results to their parents. |
||
19 | * |
||
20 | * @param array $models |
||
21 | * @param Collection $results |
||
22 | * @param string $relation |
||
23 | * @return array |
||
24 | */ |
||
25 | 1 | protected function matchSimple(array $models, Collection $results, $relation) |
|
26 | { |
||
27 | 1 | $foreign = $this->foreignKey; |
|
28 | |||
29 | 1 | $other = $this->ownerKey; |
|
30 | |||
31 | 1 | $dictionary = []; |
|
32 | |||
33 | 1 | foreach ($results as $result) { |
|
34 | 1 | $dictionary[ModelAccessor::get($result, $other)] = $result; |
|
35 | } |
||
36 | |||
37 | 1 | foreach ($models as &$model) { |
|
38 | 1 | if (isset($dictionary[ModelAccessor::get($model, $foreign)])) { |
|
39 | 1 | ModelAccessor::set($model, $relation, $dictionary[ModelAccessor::get($model, $foreign)]); |
|
40 | } |
||
41 | } |
||
42 | 1 | unset($model); |
|
43 | |||
44 | 1 | return $models; |
|
45 | } |
||
46 | |||
47 | /** |
||
48 | * Set the constraints for an eager load of the relation. |
||
49 | * |
||
50 | * @param array $models |
||
51 | * @return void |
||
52 | */ |
||
53 | 1 | public function addEagerConstraintsSimple(array $models) |
|
54 | { |
||
55 | 1 | $key = $this->related->getTable().'.'.$this->ownerKey; |
|
56 | |||
57 | 1 | $this->query->whereIn($key, $this->getEagerModelKeysSimple($models)); |
|
0 ignored issues
–
show
Bug
introduced
by
![]() |
|||
58 | 1 | } |
|
59 | |||
60 | /** |
||
61 | * Gather the keys from an array of related models. |
||
62 | * |
||
63 | * @param array $models |
||
64 | * @return array |
||
65 | */ |
||
66 | 1 | protected function getEagerModelKeysSimple(array $models) |
|
67 | { |
||
68 | 1 | $keys = []; |
|
69 | |||
70 | 1 | foreach ($models as $model) { |
|
71 | 1 | if (! is_null($value = ModelAccessor::get($model, $this->foreignKey))) { |
|
72 | 1 | $keys[] = $value; |
|
73 | } |
||
74 | } |
||
75 | |||
76 | 1 | if (count($keys) === 0) { |
|
77 | return [$this->related->getIncrementing() && |
||
78 | $this->related->getKeyType() === 'int' ? 0 : null, ]; |
||
79 | } |
||
80 | |||
81 | 1 | return array_values(array_unique($keys)); |
|
82 | } |
||
83 | } |
||
84 |