A
A
Andrew2018-01-31 14:21:40
Yii
Andrew, 2018-01-31 14:21:40

Yii2: How to make caching dependent on variable value?

Let me explain the question. I want to make news caching depending on their number. about here the problem is that if you do through

$dependency = new \yii\caching\DbDependency(['sql' => "SELECT COUNT(*) FROM news"]);

and also I have above for the pager the amount
$query = News::find();
$countQuery = $query->count();

That is, I have two requests in one place, practically, for counting the number of news. I would like to get rid of this and pass $countQuery as a dependency. How can I do that?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
E
enchikiben, 2018-01-31
@EnChikiben

$query = News::find();
$countQuery = $query->count();

$data = Yii::$app->cache->getOrSet('newsCacheKey', function () use ($query) {
   return $query->all();
}, $this->cacheDuration, new TagDependency([
   'tags' => [
      News::className() . $countQuery
   ]
]));

E
Evgeny Bukharev, 2018-01-31
@evgenybuckharev

/yiisoft/yii2/caching/TagDependency.php
See if this works

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question