1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Staudenmeir\LaravelAdjacencyList\Eloquent\Relations\Traits\Concatenation; |
4
|
|
|
|
5
|
|
|
use Illuminate\Database\Eloquent\Builder; |
6
|
|
|
use Illuminate\Database\Eloquent\Collection; |
7
|
|
|
use Illuminate\Database\Eloquent\Model; |
8
|
|
|
|
9
|
|
|
trait IsConcatenableDescendantsRelation |
10
|
|
|
{ |
11
|
|
|
use IsConcatenableRelation; |
12
|
|
|
|
13
|
|
|
/** |
14
|
|
|
* Set the constraints for an eager load of the deep relation. |
15
|
|
|
* |
16
|
|
|
* @param \Illuminate\Database\Eloquent\Builder $query |
17
|
|
|
* @param array $models |
18
|
|
|
* @return void |
19
|
|
|
*/ |
20
|
30 |
|
public function addEagerConstraintsToDeepRelationship(Builder $query, array $models): void |
21
|
|
|
{ |
22
|
30 |
|
$andSelf = $this->andSelf; |
23
|
|
|
|
24
|
30 |
|
$this->andSelf = true; |
|
|
|
|
25
|
|
|
|
26
|
30 |
|
$this->addEagerConstraints($models); |
|
|
|
|
27
|
|
|
|
28
|
30 |
|
$this->andSelf = $andSelf; |
29
|
|
|
|
30
|
30 |
|
$this->mergeExpressions($query, $this->query); |
31
|
|
|
} |
32
|
|
|
|
33
|
|
|
/** |
34
|
|
|
* Match the eagerly loaded results for a deep relationship to their parents. |
35
|
|
|
* |
36
|
|
|
* @param array $models |
37
|
|
|
* @param \Illuminate\Database\Eloquent\Collection $results |
38
|
|
|
* @param string $relation |
39
|
|
|
* @return array |
40
|
|
|
*/ |
41
|
30 |
|
public function matchResultsForDeepRelationship(array $models, Collection $results, string $relation): array |
42
|
|
|
{ |
43
|
30 |
|
$dictionary = $this->buildDictionaryForDeepRelationship($results); |
44
|
|
|
|
45
|
30 |
|
foreach ($models as $model) { |
46
|
30 |
|
$key = $model->{$this->localKey}; |
47
|
|
|
|
48
|
30 |
|
if (isset($dictionary[$key])) { |
49
|
30 |
|
$value = $this->related->newCollection($dictionary[$key]); |
50
|
|
|
|
51
|
30 |
|
$model->setRelation($relation, $value); |
52
|
|
|
} |
53
|
|
|
} |
54
|
|
|
|
55
|
30 |
|
return $models; |
56
|
|
|
} |
57
|
|
|
|
58
|
|
|
/** |
59
|
|
|
* Build the model dictionary for a deep relation. |
60
|
|
|
* |
61
|
|
|
* @param \Illuminate\Database\Eloquent\Collection $results |
62
|
|
|
* @return array |
63
|
|
|
*/ |
64
|
30 |
|
protected function buildDictionaryForDeepRelationship(Collection $results): array |
65
|
|
|
{ |
66
|
30 |
|
$pathSeparator = $this->related->getPathSeparator(); |
67
|
|
|
|
68
|
30 |
|
if (!$this->andSelf) { |
69
|
10 |
|
$results = $results->filter( |
70
|
10 |
|
fn (Model $result) => str_contains($result->laravel_through_key, $pathSeparator) |
71
|
|
|
); |
72
|
|
|
} |
73
|
|
|
|
74
|
30 |
|
return $results->mapToDictionary(function (Model $result) use ($pathSeparator) { |
75
|
30 |
|
$key = strtok($result->laravel_through_key, $pathSeparator); |
76
|
|
|
|
77
|
30 |
|
return [$key => $result]; |
78
|
30 |
|
})->all(); |
79
|
|
|
} |
80
|
|
|
} |
81
|
|
|
|