|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Volosyuk\SimpleEloquent\Relations; |
|
4
|
|
|
|
|
5
|
|
|
use Illuminate\Support\Collection; |
|
6
|
|
|
use Volosyuk\SimpleEloquent\ModelAccessor; |
|
7
|
|
|
|
|
8
|
|
|
/** |
|
9
|
|
|
* @package Volosyuk\SimpleEloquent |
|
10
|
|
|
*/ |
|
11
|
|
|
trait HasOneOrMany |
|
12
|
|
|
{ |
|
13
|
|
|
/** |
|
14
|
|
|
* Match the eagerly loaded results to their single parents. |
|
15
|
|
|
* |
|
16
|
|
|
* @param array $models |
|
17
|
|
|
* @param Collection $results |
|
18
|
|
|
* @param string $relation |
|
19
|
|
|
* @return array |
|
20
|
|
|
*/ |
|
21
|
2 |
|
protected function matchOneSimple(array $models, Collection $results, $relation) |
|
22
|
|
|
{ |
|
23
|
2 |
|
return $this->matchOneOrManySimple($models, $results, $relation, 'one'); |
|
24
|
|
|
} |
|
25
|
|
|
|
|
26
|
|
|
/** |
|
27
|
|
|
* Match the eagerly loaded results to their many parents. |
|
28
|
|
|
* |
|
29
|
|
|
* @param array $models |
|
30
|
|
|
* @param Collection $results |
|
31
|
|
|
* @param string $relation |
|
32
|
|
|
* @param string $type |
|
33
|
|
|
* @return array |
|
34
|
|
|
*/ |
|
35
|
2 |
|
protected function matchOneOrManySimple(array &$models, Collection $results, $relation, $type) |
|
36
|
|
|
{ |
|
37
|
2 |
|
$dictionary = []; |
|
38
|
|
|
|
|
39
|
2 |
|
$foreign = $this->getForeignKeyName(); |
|
|
|
|
|
|
40
|
|
|
|
|
41
|
2 |
|
foreach ($results as $result) { |
|
42
|
2 |
|
$dictionary[ModelAccessor::get($result, $foreign)][] = $result; |
|
43
|
|
|
} |
|
44
|
|
|
|
|
45
|
2 |
|
foreach ($models as &$model) { |
|
46
|
2 |
|
$key = ModelAccessor::get($model, $this->localKey); |
|
47
|
|
|
|
|
48
|
2 |
|
if (isset($dictionary[$key])) { |
|
49
|
2 |
|
$value = $this->getRelationValue($dictionary, $key, $type); |
|
|
|
|
|
|
50
|
|
|
|
|
51
|
2 |
|
ModelAccessor::set($model, $relation, $value); |
|
52
|
|
|
} |
|
53
|
|
|
} |
|
54
|
2 |
|
unset($model); |
|
55
|
|
|
|
|
56
|
2 |
|
return $models; |
|
57
|
|
|
} |
|
58
|
|
|
} |
|
59
|
|
|
|