Skip to content

Commit

Permalink
Fixed bug that the model cache cannot created when using find many
Browse files Browse the repository at this point in the history
…to get non-exists models. (#5642)
  • Loading branch information
limingxinleo committed Apr 14, 2023
1 parent d663d7b commit 37ef3ea
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 4 deletions.
4 changes: 4 additions & 0 deletions CHANGELOG-3.0.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
# v3.0.17 - TBD

## Fixed

- [#5642](https://github.com/hyperf/hyperf/pull/5642) Fixed bug that the model cache cannot created when using `find many` to get non-exists models.

## Added

- [#5634](https://github.com/hyperf/hyperf/pull/5634) Added `Hyperf\Stringable\str()` helper function.
Expand Down
13 changes: 9 additions & 4 deletions src/model-cache/src/Manager.php
Original file line number Diff line number Diff line change
Expand Up @@ -130,13 +130,18 @@ public function findManyFromCache(array $ids, string $class): Collection
// Get ids that not exist in cache handler.
$targetIds = array_diff($ids, $fetchIds);
if ($targetIds) {
/** @var Collection<int, Model> $models */
$models = $instance->newQuery()->whereIn($primaryKey, $targetIds)->get();
$dictionary = $models->getDictionary();
$ttl = $this->getCacheTTL($instance, $handler);
/** @var Model $model */
foreach ($models as $model) {
$id = $model->getKey();
$emptyTtl = $handler->getConfig()->getEmptyModelTtl();
foreach ($targetIds as $id) {
$key = $this->getCacheKey($id, $instance, $handler->getConfig());
$handler->set($key, $this->formatModel($model), $ttl);
if ($model = $dictionary[$id] ?? null) {
$handler->set($key, $this->formatModel($model), $ttl);
} else {
$handler->set($key, [], $emptyTtl);
}
}

$items = array_merge($items, $this->formatModels($models));
Expand Down
16 changes: 16 additions & 0 deletions src/model-cache/tests/ModelCacheTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -167,6 +167,22 @@ public function testFindNullBeforeCreate()
UserModel::query(true)->where('id', $id)->delete();
}

public function testFindManyNullBeforeCreate()
{
$container = ContainerStub::mockContainer();

$id = 207;

$models = UserModel::findManyFromCache([$id]);
/** @var Redis $redis */
$redis = $container->make(RedisProxy::class, ['pool' => 'default']);
$this->assertEquals(1, $redis->exists('{mc:default:m:user}:id:' . $id));
$this->assertSame(0, $models->count());

$this->assertEquals(1, $redis->del('{mc:default:m:user}:id:' . $id));
UserModel::query(true)->where('id', $id)->delete();
}

public function testIncrNotExist()
{
$container = ContainerStub::mockContainer();
Expand Down

0 comments on commit 37ef3ea

Please sign in to comment.