Skip to content

Commit ac94fce

Browse files
authored
Restire get_models_from_cache (#112)
1 parent 7fd55a4 commit ac94fce

1 file changed

Lines changed: 37 additions & 6 deletions

File tree

lib/Relation.php

Lines changed: 37 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -714,23 +714,54 @@ public function find(): Model|array
714714
}
715715

716716
$single = !is_array($args) || !array_is_list($args);
717+
$table = $this->table();
718+
if ($table->cache_individual_model) {
719+
$list = static::get_models_from_cache((array) $args);
720+
} else {
721+
$options = $this->options;
722+
$options['conditions'] ??= [];
723+
$options['conditions'][] = $this->pk_conditions($args);
717724

718-
$options = $this->options;
719-
$options['conditions'] ??= [];
720-
$options['conditions'][] = $this->pk_conditions($args);
725+
if (is_array($args) && 0 === count($args)) {
726+
throw new RecordNotFound("Couldn't find " . $this->className . ' without an ID');
727+
}
721728

722-
if (is_array($args) && 0 === count($args)) {
723-
throw new RecordNotFound("Couldn't find " . $this->className . ' without an ID');
729+
$list = $this->_to_a($options);
724730
}
725731

726-
$list = $this->_to_a($options);
727732
if (is_array($args) && count($list) != count($args)) {
728733
throw new RecordNotFound('found ' . count($list) . ', but was looking for ' . count($args));
729734
}
730735

731736
return $single ? ($list[0] ?? throw new RecordNotFound('tbd')) : $list;
732737
}
733738

739+
/**
740+
* Check cache for each primary key before querying the database.
741+
*
742+
* @param list<int|string> $pks An array of primary keys
743+
*
744+
* @return array<TModel>
745+
*/
746+
protected function get_models_from_cache(array $pks)
747+
{
748+
$models = [];
749+
$table = $this->table();
750+
751+
$options = $this->options;
752+
foreach ($pks as $pk) {
753+
$options['conditions'] ??= [];
754+
$options['conditions'][] = $this->pk_conditions((array) $pk);
755+
$models[] = Cache::get($table->cache_key_for_model($pk), function () use ($table, $options) {
756+
$res = iterator_to_array($table->find($options));
757+
758+
return $res[0] ?? null;
759+
}, $table->cache_model_expire);
760+
}
761+
762+
return array_filter($models);
763+
}
764+
734765
/**
735766
* Returns a record (or N records if a parameter is supplied) without any implied
736767
* order. The order will depend on the database implementation.

0 commit comments

Comments
 (0)