Skip to content

Commit 38fb348

Browse files
committed
Refactor builder method to cache relationships
1 parent 6b401d7 commit 38fb348

File tree

1 file changed

+18
-12
lines changed

1 file changed

+18
-12
lines changed

src/Builder.php

Lines changed: 18 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,9 @@
33
use Closure;
44
use Illuminate\Cache\TaggableStore;
55
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;
69

710
class Builder extends EloquentBuilder
811
{
@@ -12,24 +15,27 @@ protected function eagerLoadRelation(array $models, $name, Closure $constraints)
1215
$relation->addEagerConstraints($models);
1316
$constraints($relation);
1417

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+
{
1527
$parentIds = implode('_', collect($models)->pluck('id')->toArray());
1628
$parentName = str_slug(get_class($relation->getParent()));
1729
$childName = str_slug(get_class($relation->getRelated()));
18-
// $cache = cache();
19-
//
20-
// if (is_subclass_of($cache->getStore(), TaggableStore::class)) {
21-
// $cache->tags([$parentName, $childName]);
22-
// }
30+
$cache = cache();
2331

24-
$results = cache()->tags([$parentName, $childName])
32+
if (is_subclass_of($cache->getStore(), TaggableStore::class)) {
33+
$cache->tags([$parentName, $childName]);
34+
}
35+
36+
return cache()->tags([$parentName, $childName])
2537
->rememberForever("{$parentName}_{$parentIds}-{$childName}s", function () use ($relation) {
2638
return $relation->getEager();
2739
});
28-
29-
return $relation->match(
30-
$relation->initRelation($models, $name),
31-
$results,
32-
$name
33-
);
3440
}
3541
}

0 commit comments

Comments
 (0)