lolka
lolka

Reputation: 121

How to clear cache in yii2 AR?

How to clear that cache of current data?

$result = Customer::getDb()->cache(function ($db) use ($id) {
    return Customer::findOne($id);
}, 60 * 60 * 24 * 4);

I want to clear the cache of current data in Customer after updating

Upvotes: 6

Views: 9521

Answers (2)

Bizley
Bizley

Reputation: 18021

You can modify this code to use data cache instead of query cache so you can use unique key.

$data = $cache->get('customer' . $id);
if ($data === false) {
    $data = Customer::findOne($id);
    $cache->set('customer' . $id, $data, 60 * 60 * 24 * 4);
}

or starting from 2.0.11:

$data = $cache->getOrSet('customer' . $id, function () use ($id) {
    return Customer::findOne($id);
}, 60 * 60 * 24 * 4);

So now you can use

$cache->delete('customer' . $id);

Upvotes: 8

lalithkumar
lalithkumar

Reputation: 3540

you can use flush for global.

Yii::$app->cache->flush();

you can use TagDependency :

$result = Customer::getDb()->cache(function ($db) use ($id) {
    return Customer::findOne($id);
}, 60 * 60 * 24 * 4, new TagDependency(['tags'=>'customer']));

//to flush
TagDependency::invalidate(Yii::$app->cache, 'customer');

For more information check here

Upvotes: 2

Related Questions