Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to flush db query cache in yii2?

How to handle it when some changes happen in specific table records ?

public static function getAirportWithCache($iata_code){

              $result = Airports::getDb()->cache(function ($db) use ($iata_code){
                     $res = Airports::find()
                               ->where(['iata_code' => $iata_code])
                               ->limit(1)
                               ->asArray()
                               ->one();
                     return $res;
              });
              return $result;
        }
like image 872
Yatin Mistry Avatar asked Feb 08 '16 12:02

Yatin Mistry


3 Answers

For global cache, can use :

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

for spesific you can use TagDependency :

 //way to use
return Yii::$app->db->cache(function(){
    $query =  new Query();
    return $query->all();
}, 0, new TagDependency(['tags'=>'cache_table_1']));

//way to flush when modify table
TagDependency::invalidate(Yii::$app->cache, 'cache_table_1');

see the documentation http://www.yiiframework.com/doc-2.0/yii-caching-tagdependency.html

like image 190
Surya Sheillendra Avatar answered Oct 19 '22 20:10

Surya Sheillendra


You should simply use \yii\caching\DbDependency, e.g. :

public static function getAirportWithCache($iata_code){
    // for example if airports count change, this will update your cache
    $dependency = new \yii\caching\DbDependency(['sql' => 'SELECT COUNT(*) FROM ' . Airports::tableName()]);
    $result = Airports::getDb()->cache(function ($db) use ($iata_code){
        return Airports::find()
            ->where(['iata_code' => $iata_code])
            ->limit(1)
            ->asArray()
            ->one();
    }, 0, $dependency);
    return $result;
}

Read more...

like image 4
soju Avatar answered Oct 19 '22 20:10

soju


Just execute Yii::$app->cache->flush(); anywhere (probably in your controller)

PS: It will delete entire cache stored in your server

like image 2
Sohel Ahmed Mesaniya Avatar answered Oct 19 '22 19:10

Sohel Ahmed Mesaniya