Answer the question
In order to leave comments, you need to log in
How to cache database queries in Yii2?
Good evening. How to save the cache in the framework? There are a lot of topics, I know, and examples, but they are not clear and do not work, at least for me, apparently I'm doing something wrong.
protected function cacheGet($keyCache, $dbData){
$cache = \Yii::$app->cache;
$data = $cache->get($keyCache);
if ($data !== $dbData) {
$data = $dbData;
$cache->set($keyCache, $data);
}
return $data;
}
public function actionIndex(){
$articlesNew = $this->cacheGet('articlesNewIndex', ForecastArticle::find()->asArray()->orderBy('id desc')->limit(4)->all());
$articles = $this->cacheGet('articlesIndex', ForecastArticle::find()->asArray()->orderBy('id desc')->limit(10)->with('comments')->all());
$countComment = $this->foreachCommentCountIsArticle($articles);
return $this->render('index',
compact(
'articlesNew',
'articles',
'countComment'
)
);
}
Answer the question
In order to leave comments, you need to log in
$result = Customer::getDb()->cache(function ($db) {
return Customer::find()->where(['id' => 1])->one();
});
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question