How to create or update a model cache record?

before create a account, i will find a record using model cache:

public function oneByFiled($value, $field = 'id')
        return self::findFirst([
            'conditions' => $field . ' = ?0',
            'bind' => $value,
            'cache' => ['key' => sprintf('%s:%s:%s', $this->getSource(), $field, $value), 'lifetime' => 600],

then, create account record:

$userAccount = new UserAccounts();
$result = $userAccount->create([
        'username' => $this->request->getPost('username'),
        'password' => password_hash($this->request->getPost('password'), PASSWORD_DEFAULT),

a new account record has been added to mysql, but when i call oneByFiled(), it read from redis, return false.

how to insert a model cache record when create a row, and how to update a model cache record when update a mysql row?

Hi @Hisune the most simple way is make a cache only when you find it and remove them when update/remove.

To remove them after remove or update you must have a behavior mounted in your model like this

use Phalcon\Di;
use Phalcon\Mvc\Model\Behavior;
use Phalcon\Mvc\Model\BehaviorInterface;

class RemoveCachedModel extends Behavior implements BehaviorInterface
    public function notify($eventType, $model)
        if ($eventType === 'afterDelete' || $eventType === 'afterUpdate') {
            if (Di::getDefault()->get('modelsCache')->exists(/*here your cache key*/)) {
                Di::getDefault()->get('modelsCache')->delete(/*here your cache key*/);

Other way more complex is using snapshots and checking is the model change to remove or not

Good luck


work perfect. thx!