Abudayah
Abudayah

Reputation: 3875

Yii app updateCounters (page views) best way?

I have a Yii Powered web app with a controller (PostController) and a "view" column in database.

How can I update these rows when visitors view Post page?

Now my code is working, but is it correct or are there any comments/suggestions?

public function actionView($id)
{
    $this->render('view',array(
        'model'=>$this->loadModel($id),
    ));
    Quotes::model()->updateCounters(array('views'=>+1), 'id=' . $id );
}

Upvotes: 1

Views: 2806

Answers (3)

Footniko
Footniko

Reputation: 2752

Since 1.1.8, you can use such code:

$this->saveCounters(array('views'=>1));

It would be faster. See more information here: http://www.yiiframework.com/doc/api/1.1/CActiveRecord#saveCounters-detail

Upvotes: 1

hanzo
hanzo

Reputation: 61

in the Quotes model:

public function afterFind() {
    $this->view++;
    $this->save();
}

this will update views everytime after find. in controller:

public function actionView($id)
{
    $this->render('view',array(
        'model'=>$this->loadModel($id),//or 'model'=>Quotes::model()->findByPk($id)
    ));
}

Upvotes: 2

topscoder
topscoder

Reputation: 79

You need to create a Model for your Post. If you name that model for example Post (if you don't already have that). You need to update the value using this PHP code:

Post::model()->updateByPk(1, array('view' => 2));

Assuming your row has an ID with value 1 (Page ID for example) and you want to update the view column with the value 2.

The type of your model is CActiveRecord. Find great documentation at: http://www.yiiframework.com/doc/api/1.1/CActiveRecord#updateByPk-detail

Upvotes: 0

Related Questions