如何在yii2中刷新数据库查询缓存?

如何在yii2中刷新数据库查询缓存?,yii2,query-cache,Yii2,Query Cache,当特定表记录中发生某些更改时,如何处理它 public static function getAirportWithCache($iata_code){ $result = Airports::getDb()->cache(function ($db) use ($iata_code){ $res = Airports::find() ->where(

当特定表记录中发生某些更改时,如何处理它

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;
        }

只需执行
Yii::$app->cache->flush()任意位置(可能在控制器中)

PS:它将删除存储在服务器中的整个缓存

您只需使用,例如:


…对于全局缓存,可以使用:

Yii::$app->cache->flush();
对于spesific,您可以使用标记相关性:

 //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');

请参阅文档

我将进行检查。以及如何处理特定于表的记录中发生的任何更改?这也将删除我的整个缓存。我想为db查询指定一个特定的解决方案。这肯定不是解决方案,因为它会刷新整个缓存。这意味着查询缓存、rbac缓存、模式缓存,除了连接了多个缓存组件外,其他所有内容都可以使用。在db查询中,我没有特定的键。像Yii::$app->cache->delete($key);在我的示例中,如何操作?为缓存设置特定的键,然后调用delete()。使用Try:
Yii::$app->cache->set('dbCache',$result,0,null)
No。它不工作。正如@SohelAhmedM所建议的,它可以工作,但会删除所有缓存数据。这应该被接受为答案,因为根据yii2规范,这是正确的解决方案!我曾想过这样做,但我怎么知道数据何时发生了变化?要知道这一点,难道它不需要通过查询来发现,从而从一开始就违背了缓存的目的吗!?感谢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');