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);
});
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);
}
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) Use cache like that:
2) If you may use query dependency, use like that:
I too am having trouble with this. Here's my workaround for the time being for a hasOne() relationship.
I only want to cache data for the current request, so this works. However because I'm using
->one();
it does not return the ActiveQuery object if we call$model->getGroup()
(which I found is good for extending queries)Unfortunately if I do return the ActiveQuery object, Yii2 does some "magic" on it and always does a SELECT * which I can't control.
Since 2.0.14 you can use the following shortcuts:
Source: https://www.yiiframework.com/doc/guide/2.0/en/caching-data