Incrementing Cakephp database field by a value

时间秒杀一切 提交于 2019-11-27 23:01:29
mark

you can use updateAll() for this

a little googling reveals this pretty quick: http://cakephp.1045679.n5.nabble.com/Auto-Increment-A-Field-td3491697.html

Andre S

I used updateAll in my code to increment views in an article. Therefore, every time an article is visited, I call the following function from within my view action in my articles controller:

function incrementViewCount($id) {
    $this->updateAll(
        array('Article.viewed' => 'Article.viewed+1'),                    
        array('Article.id' => $id)
    );
}

Then in your controller…

$this->MyModel->incrementViewCount(123);

Basically similar to the tutorial suggested in the previous answer.

You can try this code also. Works fine for simple ++/-- operations without the need of additional querying.

https://gist.github.com/denchev/8209318

Using saveField:

<?php

$this->Article->id = $id;
$this->Article->saveField('viewed', (int)$this->Article->field('viewed') + 1);

?>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!