A
A
Andrey Nikitin2021-01-21 14:46:35
Yii
Andrey Nikitin, 2021-01-21 14:46:35

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.

There is a ForecastController and a method in it

protected function cacheGet($keyCache, $dbData){
        $cache = \Yii::$app->cache;
        $data = $cache->get($keyCache);
        if ($data !== $dbData) {
            $data = $dbData;
            $cache->set($keyCache, $data);
        }
        return $data;
    }



in the action I call it

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'
            )
        );
    }



Everything is well saved in the cache, there are no questions. But queries to the database still remain ..... What am I doing wrong?
I already think, maybe while adding an article from the admin panel, save it to the cache and pull only the cache on the front.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alex Glebov, 2021-01-21
@andreyNi

$result = Customer::getDb()->cache(function ($db) {
    return Customer::find()->where(['id' => 1])->one();
});

https://www.yiiframework.com/doc/guide/2.0/ru/cach...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question