Skip to content

Commit

Permalink
Support deeply nested cache relations for model-cache. (#5641)
Browse files Browse the repository at this point in the history
  • Loading branch information
limingxinleo committed Apr 14, 2023
1 parent 90feb18 commit d663d7b
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 1 deletion.
1 change: 1 addition & 0 deletions CHANGELOG-3.0.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

- [#5634](https://github.com/hyperf/hyperf/pull/5634) Added `Hyperf\Stringable\str()` helper function.
- [#5639](https://github.com/hyperf/hyperf/pull/5639) Added `Redis::pipeline()` and `Redis::transaction()` support.
- [#5641](https://github.com/hyperf/hyperf/pull/5641) Support deeply nested cache relations for `model-cache`.

## Optimized

Expand Down
14 changes: 13 additions & 1 deletion src/model-cache/src/EagerLoad/EagerLoaderBuilder.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
use Closure;
use Hyperf\Collection\Arr;
use Hyperf\Database\Model\Builder;
use Hyperf\Database\Model\Collection;
use Hyperf\Database\Model\Relations\Relation;
use Hyperf\ModelCache\CacheableInterface;

Expand Down Expand Up @@ -47,7 +48,18 @@ protected function getEagerModels(Relation $relation)
$column = sprintf('%s.%s', $model->getTable(), $model->getKeyName());

if ($model instanceof CacheableInterface && $this->couldUseEagerLoad($wheres, $column)) {
return $model::findManyFromCache($wheres[0]['values'] ?? []);
$models = $model::findManyFromCache($wheres[0]['values'] ?? []);
// If we actually found models we will also eager load any relationships that
// have been specified as needing to be eager loaded, which will solve the
// n+1 query issue for the developers to avoid running a lot of queries.
if ($models->count() > 0 && $with = $relation->getEagerLoads()) {
$first = $models->first();
$self = (new static($this->query->newQuery()));
$builder = $first->registerGlobalScopes($self->setModel($first))->setEagerLoads($with);
$models = new Collection($builder->eagerLoadRelations($models->all()));
}

return $models;
}

return $relation->getEager();
Expand Down

0 comments on commit d663d7b

Please sign in to comment.