1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Volosyuk\SimpleEloquent\Relations; |
4
|
|
|
|
5
|
|
|
use Illuminate\Database\Eloquent\Model; |
6
|
|
|
use Illuminate\Support\Collection; |
7
|
|
|
use stdClass; |
8
|
|
|
use Volosyuk\SimpleEloquent\Builder; |
9
|
|
|
use Volosyuk\SimpleEloquent\ModelAccessor; |
10
|
|
|
|
11
|
|
|
/** |
12
|
|
|
* Trait SimpleRelation |
13
|
|
|
* @package Volosyuk\SimpleEloquent |
14
|
|
|
* |
15
|
|
|
* @property Builder $query |
16
|
|
|
* @property Model $parent |
17
|
|
|
*/ |
18
|
|
|
trait Relation |
19
|
|
|
{ |
20
|
|
|
/** |
21
|
|
|
* @param $models |
22
|
|
|
* @param $name |
23
|
|
|
* @return array |
24
|
|
|
*/ |
25
|
10 |
|
public function eagerLoadAndMatchSimple($models, $name) |
26
|
|
|
{ |
27
|
10 |
|
$results = $this->getEagerSimple(); |
28
|
|
|
|
29
|
10 |
|
return $this->matchSimple($models, $results, $name); |
|
|
|
|
30
|
|
|
} |
31
|
|
|
|
32
|
|
|
/** |
33
|
|
|
* @param array $models |
34
|
|
|
* @param $relation |
35
|
|
|
* @return array|stdClass[] |
36
|
|
|
*/ |
37
|
11 |
|
public function initSimpleRelation(array &$models, $relation) |
38
|
|
|
{ |
39
|
11 |
|
foreach ($models as &$model) { |
40
|
11 |
|
ModelAccessor::set($model, $relation, null); |
41
|
|
|
} |
42
|
11 |
|
unset($model); |
43
|
|
|
|
44
|
11 |
|
return $models; |
45
|
|
|
} |
46
|
|
|
|
47
|
|
|
/** |
48
|
|
|
* Get the relationship for eager loading. |
49
|
|
|
* |
50
|
|
|
* @return Collection |
51
|
|
|
*/ |
52
|
10 |
|
protected function getEagerSimple() |
53
|
|
|
{ |
54
|
10 |
|
return $this->getSimple(); |
|
|
|
|
55
|
|
|
} |
56
|
|
|
|
57
|
|
|
/** |
58
|
|
|
* Get all of the primary keys for an array of models. |
59
|
|
|
* |
60
|
|
|
* @param array $models |
61
|
|
|
* @param string $key |
62
|
|
|
* @return array |
63
|
|
|
*/ |
64
|
7 |
|
protected function getKeys(array $models, $key = null) |
65
|
|
|
{ |
66
|
|
|
return array_unique(array_values(array_map(function ($value) use ($key) { |
67
|
7 |
|
return $key ? ModelAccessor::get($value, $key) : ModelAccessor::get($value, $this->parent->getKeyName()); |
68
|
7 |
|
}, $models))); |
69
|
|
|
} |
70
|
|
|
|
71
|
|
|
/** |
72
|
|
|
* Set the constraints for an eager load of the relation. |
73
|
|
|
* |
74
|
|
|
* @param array $models |
75
|
|
|
* @return void |
76
|
|
|
*/ |
77
|
4 |
|
public function addEagerConstraintsSimple(array $models) |
78
|
|
|
{ |
79
|
4 |
|
$this->query->whereIn($this->getQualifiedForeignKeyName(), $this->getKeys($models)); |
|
|
|
|
80
|
4 |
|
} |
81
|
|
|
} |
82
|
|
|
|