dongnu4254 2017-06-23 13:13 采纳率: 100%
浏览 37

如何在Yii Framework 2中使用ActiveRecord和Pagination实现缓存?

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?

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
    • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
    • ¥20 有关区间dp的问题求解
    • ¥15 多电路系统共用电源的串扰问题
    • ¥15 slam rangenet++配置
    • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
    • ¥15 ubuntu子系统密码忘记
    • ¥15 保护模式-系统加载-段寄存器
    • ¥15 电脑桌面设定一个区域禁止鼠标操作
    • ¥15 求NPF226060磁芯的详细资料