Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We鈥檒l occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support deeply nested cache relations for model-cache. #5641

Merged
merged 3 commits into from
Apr 14, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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