How To Count That How Many Times A Page Is Viewed.

Hello guys.

I am currently working on a project in which I want to save the record that how many times a post is being viewed by users.

I have create a field in the post table and I want to update this field after a post page is viewed by the user.

and after that I will display a list on front end with mostly read a post page.

How can I do this ?

I have tried this method but its not working


protected function afterFind() {

        parent::afterFind();

        $this->_oldTags = $this->tags;

        $this->views++;

        $this->save();

    } 

and error is

CDbCommand failed to execute the SQL statement: SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (almunajjid-db.post, CONSTRAINT post_ibfk_3 FOREIGN KEY (updated_by) REFERENCES admin (id) ON DELETE CASCADE ON UPDATE CASCADE). The SQL statement executed was: UPDATE post SET id=:yp0, category_id=:yp1, post_type=:yp2, title=:yp3, slug=:yp4, description=:yp5, excerpt=:yp6, password=:yp7, cover_photo=:yp8, tags=:yp9, file=:yp10, external_link=:yp11, views=:yp12, duration=:yp13, comment_count=:yp14, status=:yp15, is_featured=:yp16, is_sticky=:yp17, created_by=:yp18, updated_by=:yp19, published_date=:yp20, create_time=:yp21, last_update=:yp22 WHERE post.id=8

Thanks in advance.

You only should update the column ‘views’, not the whole record.

There exists a method saveCounters of the CActiveRecord that will increment a column value.




$postRecord->saveCounters(array('view_count'=>1));




protected function afterFind() {

        parent::afterFind();

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

    } 




But take care, that the default value of the views column is 0 (not null).

See this topic.

I didn’t know that there is a method ‘saveCounters()’ before reading this topic.

How about updating the $model->view attribute in the actionView()

You might want to consider a ready made extension for this. I released in the past such an extension. You can review it here.