Answer the question
In order to leave comments, you need to log in
How to save data to cache in yii2 along with page pagination?
Good afternoon! The problem is this. You need to save the page/component to the cache with the pagination of this page.
I read the docks, tried everything that was there, unfortunately it turns out not the result that you need.
In general, I add behaviors to the controller,
public function behaviors()
{
return [
'pageCache' =>
[
'class' => 'yii\filters\PageCache',
'only' => ['single'],
'duration' => 6000,
'variations' => [
[Yii::$app->request->get('page')],
],
'dependency' => [
'class' => DbDependency::class,
'sql' => 'SELECT COUNT(*) FROM article',
],
],
];
}
<?if($this->beginCache('artIndex', ['dependency' => $dependency])):?>
<?foreach ($articles as $article):?>
<div class="col-md-6">
<?= Html::a(Html::img("@web/".$article->image,
['alt' => 'картинка']) .
"<div class='blog-content-body'>
<div class='post-meta'>
<span class='category'>{$article->category->title}</span>
<span class='mr-2'>{$article->dateSave}</span> •
<span class='ml-2'><span class='fa fa-comments'></span> 3</span>
</div>
<h2>{$article->title}</h2>
</div>",
[
// 'article/single', 'id' => $article->id
'article/single', 'slug' => $article->slug
],
[
'class'=>'blog-entry element-animate', 'data-animate-effect'=>'fadeIn'
]
)
?>
</div>
<?endforeach;?>
<?$this->endCache()?>
<?endif;?>
public function behaviors()
{
return [
'CachedBehavior' => [
'class' => CachedBehavior::class,
'cache_key' => [
'artIndex',
],
]
];
}
Answer the question
In order to leave comments, you need to log in
In general, I figured it out, maybe it will be useful to someone, in
public function actionIndex(){
$query = Article::getArticleDesc();
$data = $this->cacheGet('artIndex');
if ($data === false) {
$pages = new Pagination([
'totalCount' => $query->count(),
'pageSize' => 20,
'forcePageParam' => false,
'pageSizeParam' => false
]);
$articles = $query->offset($pages->offset)->limit($pages->limit)->all();
$this->cacheSet('artIndex', $articles, 10000);
return $this->render('index', compact('articles', 'pages'));
}
$pages = new Pagination([
'totalCount' => $query->count(),
'pageSize' => 20,
'forcePageParam' => false,
'pageSizeParam' => false
]);
$articles = $query->offset($pages->offset)->limit($pages->limit)->all();
return $this->render('index', compact('articles', 'pages'));
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question