Incrementing Cakephp database field by a value

techie_28 picture techie_28 · Dec 31, 2011 · Viewed 10.6k times · Source

I have this field whose value i have to increment the field value by a specific value. I am using this

$data['quantity']     = 'Order.quantity+1';

which doesnt works for me quantity is a integer coloumn here. Also will it work when nothing is in database?.

Regards Himanshu Sharma

Answer

AKKAweb picture AKKAweb · Jan 1, 2012

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.