|
1
|
|
|
<?php namespace GeneaLabs\LaravelModelCaching; |
|
2
|
|
|
|
|
3
|
|
|
use Closure; |
|
4
|
|
|
use Illuminate\Cache\TaggableStore; |
|
5
|
|
|
use Illuminate\Database\Eloquent\Builder as EloquentBuilder; |
|
6
|
|
|
use Illuminate\Database\Eloquent\Relations\Pivot; |
|
7
|
|
|
use Illuminate\Support\Collection; |
|
8
|
|
|
use Illuminate\Database\Eloquent\Relations\Relation; |
|
9
|
|
|
|
|
10
|
|
|
class Builder extends EloquentBuilder |
|
11
|
|
|
{ |
|
12
|
|
|
protected function eagerLoadRelation(array $models, $name, Closure $constraints) |
|
13
|
|
|
{ |
|
14
|
|
|
$relation = $this->getRelation($name); |
|
15
|
|
|
$relation->addEagerConstraints($models); |
|
16
|
|
|
$constraints($relation); |
|
17
|
|
|
|
|
18
|
|
|
return $relation->match( |
|
19
|
|
|
$relation->initRelation($models, $name), |
|
20
|
|
|
$this->cacheResults($relation, $models), |
|
21
|
|
|
$name |
|
22
|
|
|
); |
|
23
|
|
|
} |
|
24
|
|
|
|
|
25
|
|
|
protected function cacheResults(Relation $relation, array $models) : Collection |
|
26
|
|
|
{ |
|
27
|
|
|
$parentIds = implode('_', collect($models)->pluck('id')->toArray()); |
|
28
|
|
|
$parentName = str_slug(get_class($relation->getParent())); |
|
29
|
|
|
$childName = str_slug(get_class($relation->getRelated())); |
|
30
|
|
|
$cache = cache(); |
|
31
|
|
|
|
|
32
|
|
|
if (is_subclass_of($cache->getStore(), TaggableStore::class)) { |
|
33
|
|
|
$cache->tags([$parentName, $childName]); |
|
34
|
|
|
} |
|
35
|
|
|
|
|
36
|
|
|
return cache()->tags([$parentName, $childName]) |
|
37
|
|
|
->rememberForever("{$parentName}_{$parentIds}-{$childName}s", function () use ($relation) { |
|
38
|
|
|
return $relation->getEager(); |
|
39
|
|
|
}); |
|
40
|
|
|
} |
|
41
|
|
|
} |
|
42
|
|
|
|