Yii2 ActiveRecord 缓存 [英] Yii2 ActiveRecord cache
本文介绍了Yii2 ActiveRecord 缓存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
Yii 2 如何使用 ActiveRecotd 缓存?我没有在官方文档中找到任何示例.在 Google 中我找到了 2 个例子,第一个是:
How to use ActiveRecotd cache for Yii 2? I did't find any examples in official docs. In Google I found 2 examples, first is:
$db = self::getDb();
$object = $db->cache(function ($db) use($id) {
return self::findOne($id);
});
但它不适用于 Model
,我使用更新的框架进行了测试.另一个例子是:
But it doesn't work for Model
, I tested with updated framework. Other example is:
$data = Yii::$app->cache->get('some_var_' . $id);
if ($data === false)
{
$data = self::findOne($id);
Yii::$app->cache->set('some_var_' . $id, $data, 60);
}
它工作正常,但它不是 ActiveRecord 缓存而是数据缓存,所以我们在 Yii 2 中没有 ActiveRecord 缓存?
It's working fine, but it's not ActiveRecord caching it's data caching, So we haven't got ActiveRecord caching in Yii 2?
推荐答案
1) 像这样使用缓存:
1) Use cache like that:
$db = Yii::$app->db;// or Category::getDb()
$result = $db->cache(function ($db) use ($id) {
return Category::find()->where(['id' => $id])->all();
}, CACHE_TIMEOUT);
2) 如果你可以使用查询依赖,像这样使用:
2) If you may use query dependency, use like that:
$db = Yii::$app->db;// or Category::getDb()
$dep = new DbDependency();
$dep->sql = 'SELECT count(*) FROM category';
$result = $db->cache(function ($db) use ($id) {
return Category::find()->where(['id' => $id])->all();
}, CACHE_TIMEOUT, $dep);
这篇关于Yii2 ActiveRecord 缓存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文