1 | <?php |
||
2 | |||
3 | namespace Staudenmeir\LaravelMergedRelations\Eloquent; |
||
4 | |||
5 | use Illuminate\Database\Eloquent\Builder as Base; |
||
6 | use Illuminate\Database\Eloquent\Collection; |
||
7 | use Illuminate\Database\Eloquent\Relations\Relation; |
||
8 | |||
9 | class Builder extends Base |
||
10 | { |
||
11 | /** |
||
12 | * Get the hydrated models without eager loading. |
||
13 | * |
||
14 | * @param array $columns |
||
15 | * @return \Illuminate\Database\Eloquent\Model[] |
||
16 | */ |
||
17 | public function getModels($columns = ['*']) |
||
18 | { |
||
19 | $items = $this->query->get($columns)->all(); |
||
20 | |||
21 | $models = []; |
||
22 | |||
23 | foreach ($items as $item) { |
||
24 | $class = Relation::getMorphedModel($item->laravel_model) ?? $item->laravel_model; |
||
25 | |||
26 | $unset = ['laravel_model', 'laravel_placeholders']; |
||
27 | |||
28 | if ($item->laravel_placeholders) { |
||
29 | array_push($unset, ...explode(',', $item->laravel_placeholders)); |
||
30 | } |
||
31 | |||
32 | foreach ($unset as $key) { |
||
33 | unset($item->$key); |
||
34 | } |
||
35 | |||
36 | $models[] = (new $class())->hydrate([$item])[0]; |
||
37 | } |
||
38 | |||
39 | return $models; |
||
40 | } |
||
41 | |||
42 | /** |
||
43 | * Eager load the relationships for the models. |
||
44 | * |
||
45 | * @param array $models |
||
46 | * @return array |
||
47 | */ |
||
48 | public function eagerLoadRelations(array $models) |
||
49 | { |
||
50 | collect($models)->groupBy(function ($model) { |
||
0 ignored issues
–
show
Bug
introduced
by
![]() |
|||
51 | return get_class($model); |
||
52 | })->each(function ($models) { |
||
53 | $model = $models[0]; |
||
54 | |||
55 | $relations = array_merge( |
||
56 | $this->eagerLoad, |
||
57 | $model->laravel_with ? explode(',', $model->laravel_with) : [] |
||
58 | ); |
||
59 | |||
60 | (new Collection($models))->load($relations); |
||
61 | }); |
||
62 | |||
63 | foreach ($models as $model) { |
||
64 | unset($model->laravel_with); |
||
65 | } |
||
66 | |||
67 | return $models; |
||
68 | } |
||
69 | } |
||
70 |