如何在 yii2 ActiveRecord 中使用查询缓存

How to use query caching in yii2 ActiveRecord

我引用的是指南:

``查询缓存是一种建立在数据缓存之上的特殊缓存功能。提供缓存数据库查询结果。

查询缓存需要数据库连接和有效的缓存应用程序组件。查询缓存的基本用法如下,假设$db是一个yii\db\Connection实例:

$result = $db->cache(function ($db) {

    // the result of the SQL query will be served from the cache
    // if query caching is enabled and the query result is found in the cache
    return $db->createCommand('SELECT * FROM customer WHERE id=1')->queryOne();

});

``

我不认为我会在 AR 中手动创建数据库连接 类。那么如何在我的 AR 模型中做到这一点?

我在 yii2 论坛上问过 the same question 但我没有得到答案。好像很多人都不知道Active Record里面怎么做query caching。

也许这有帮助:yii2 issues on github

qiangxue commented on 11 Jan 2014

In 2.0, you need to use the following code:

$db->beginCache();
// your db query code here...
$db->endCache();

Yii 2 现在需要闭包来包装查询。 AR 最终会进行查询,因此您可以将其放入闭包中。在 AR class 中,获取数据库并包装您要使用的查询。闭包有一个签名 function($db) 并且你通常需要访问更多的变量,所以添加 use($variable) 让变量可见在闭包内。

    $db = self::getDb();
    $object = $db->cache(function ($db) use($id) {
        return self::findOne($id);
    });

如果您写入数据库,上面的缓存在缓存持续时间到期之前不会知道它。所以应该在缓存函数中添加依赖,告诉它什么时候使缓存失效。依赖性很快变得复杂...... http://www.yiiframework.com/doc-2.0/yii-caching-dependency.html