Yii2 ActiveRecord Cache

How to use ActiveRecotd cache for Yii 2? I did not find examples in official docs. I found 2 examples on Google, first of all:

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

But this does not work for Model , I tested the updated framework. Another example:

 $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 works fine, but it's not ActiveRecord caching data caching, so we don't have ActiveRecord caching in Yii 2?

+5
source share
2 answers

1) Use the cache as follows:

 $db = Yii::$app->db;// or Category::getDb() $result = $db->cache(function ($db) use ($id) { return Category::find()->where(['id' => $id])->all(); }, CACHE_TIMEOUT); 

2) If you can use a query dependency, use this:

 $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); 
+6
source

I also have problems with this. Here is my workaround for the hasOne () relation.

 public function getGroup() { if(isset(static::$_getGroup[$this->id])) { return static::$_getGroup[$this->id]; } $Group = $this->hasOne(BillChargesGroup::className(), ['id' => 'group_id'])->one(); static::$_getGroup[$this->id] = $Group; return $Group; } 

I only want to cache data for the current request, so this works. However, since I use ->one(); , it does not return an ActiveQuery object if we call $model->getGroup() (which I found useful for extending queries)

Unfortunately, if I return an ActiveQuery object, Yii2 does some β€œmagic” on it and always does SELECT *, which I cannot control.

+2
source

All Articles