|
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
|
9 |
|
public function eagerLoadAndMatchSimple($models, $name) |
|
26
|
|
|
{ |
|
27
|
9 |
|
$results = $this->getEagerSimple(); |
|
28
|
|
|
|
|
29
|
9 |
|
return $this->matchSimple($models, $results, $name); |
|
|
|
|
|
|
30
|
|
|
} |
|
31
|
|
|
|
|
32
|
|
|
/** |
|
33
|
|
|
* @param array $models |
|
34
|
|
|
* @param $relation |
|
35
|
|
|
* @return array|stdClass[] |
|
36
|
|
|
*/ |
|
37
|
10 |
|
public function initSimpleRelation(array &$models, $relation) |
|
38
|
|
|
{ |
|
39
|
10 |
|
foreach ($models as &$model) { |
|
40
|
10 |
|
ModelAccessor::set($model, $relation, null); |
|
41
|
|
|
} |
|
42
|
10 |
|
unset($model); |
|
43
|
|
|
|
|
44
|
10 |
|
return $models; |
|
45
|
|
|
} |
|
46
|
|
|
|
|
47
|
|
|
/** |
|
48
|
|
|
* Get the relationship for eager loading. |
|
49
|
|
|
* |
|
50
|
|
|
* @return Collection |
|
51
|
|
|
*/ |
|
52
|
9 |
|
protected function getEagerSimple() |
|
53
|
|
|
{ |
|
54
|
9 |
|
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
|
|
|
protected function getKeys(array $models, $key = null) |
|
65
|
|
|
{ |
|
66
|
6 |
|
return array_unique(array_values(array_map(function ($value) use ($key) { |
|
67
|
6 |
|
return $key ? ModelAccessor::get($value, $key) : ModelAccessor::get($value, $this->parent->getKeyName()); |
|
68
|
6 |
|
}, $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
|
|
|
|