F
F
Fridary2018-07-06 18:10:44
Yii
Fridary, 2018-07-06 18:10:44

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

1 answer(s)
Z
zxscv, 2018-07-06
@zxscv

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 question

Ask a Question

731 491 924 answers to any question