Answer the question
In order to leave comments, you need to log in
Yii2: How to reduce the number of queries to db in behaviors()?
On my Yii2, I make 3 identical queries to the database, which increases the page load time. How to reduce to 1?
public function behaviors()
{
return [
'httpCache' => [
'class' => 'yii\filters\HttpCache',
'only' => ['view'],
'lastModified' => function ($action, $params) {
$post = $this->findModel(Yii::$app->request->get('id'));
return strtotime($post->updated);
},
'etagSeed' => function ($action, $params) {
$post = $this->findModel(Yii::$app->request->get('id'));
return serialize([$post->updated, $post->views, $post->comments, Yii::$app->user->isGuest ? 0 : 1]);
}
],
];
}
public function actionView($id)
{
$model = $this->findModel($id);
return $this->render('view', [
'model' => $model,
]);
}
Answer the question
In order to leave comments, you need to log in
public function behaviors()
{
$post = $this->findModel(Yii::$app->request->get('id'));
return [
'httpCache' => [
'class' => 'yii\filters\HttpCache',
'only' => ['view'],
'lastModified' => function ($action, $params) use ($post){
return strtotime($post->updated);
},
'etagSeed' => function ($action, $params) use ($post) {
return serialize([$post->updated, $post->views, $post->comments, Yii::$app->user->isGuest ? 0 : 1]);
}
],
];
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question