I would like implement cache for the results of ActiveRecord
with pagination implemented. But the pagination button does not query next records. It keeps showing the same first 15 records even I click on another page number. Assume 15 is the pageSize
.
This is how my code in the controller looks like.
$query = Article::find()->where(['status' => 1]);
// get the total number of articles (but do not fetch the article data yet)
$count = $query->count();
// create a pagination object with the total count
$pagination = new Pagination(['totalCount' => $count, 'pageSize' => 15]);
// limit the query using the pagination and retrieve the articles
$query = $query->offset($pagination->offset)->limit($pagination->limit);
$userId = Yii::$app->user->identity->id;
$articles = Yii::$app->cache->getOrSet($userId, function () use($query) {
return $query->all();
});
return $this->render('inbox', [
'articles' => $articles,
'pagination' => $pagination,
]);
Below is my view
.
foreach($articles as $article) {
//...
}
<?= LinkPager::widget(['pagination' => $pagination, ]) ?>
How to implement cache
with ActiveRecord
and Pagination
in Yii framework 2?