Skip to content

Commit

Permalink
Merge pull request #5 from iksaku/enhancement/fast-find
Browse files Browse the repository at this point in the history
enhancement: Fast Find for non-searchable Models
  • Loading branch information
stevebauman authored Oct 10, 2024
2 parents 34e4bbc + c153717 commit 4b9a528
Showing 1 changed file with 22 additions and 6 deletions.
28 changes: 22 additions & 6 deletions src/Query.php
Original file line number Diff line number Diff line change
Expand Up @@ -31,11 +31,19 @@ public function __construct(
*/
public function find(?string $id): ?Model
{
if (! is_null($id)) {
if (is_null($id)) {
return null;
}

if (! empty($this->model->getSearchable())) {
return $this->whereKey($id)->first();
}

return null;
if (! $this->cache->exists($hash = $this->model->getBaseHashWithKey($id))) {
return null;
}

return $this->newModelFromHash($hash);
}

/**
Expand Down Expand Up @@ -218,10 +226,7 @@ public function chunk(int $count, Closure $callback): void
$models = $this->model->newCollection();

foreach ($chunk as $hash) {
$models->add($this->model->newFromBuilder([
...$this->cache->getAttributes($hash),
$this->model->getKeyName() => $this->getKeyValue($hash),
]));
$models->add($this->newModelFromHash($hash));
}

if ($callback($models) === false) {
Expand All @@ -230,6 +235,17 @@ public function chunk(int $count, Closure $callback): void
}
}

/**
* Create a new model instance from the given hash.
*/
protected function newModelFromHash(string $hash): Model
{
return $this->model->newFromBuilder([
...$this->cache->getAttributes($hash),
$this->model->getKeyName() => $this->getKeyValue($hash),
]);
}

/**
* Get the model key's value from the given hash.
*/
Expand Down

0 comments on commit 4b9a528

Please sign in to comment.