Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Incrementing Cakephp database field by a value

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

like image 520
techie_28 Avatar asked Dec 31 '11 16:12

techie_28


4 Answers

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.

like image 138
AKKAweb Avatar answered Nov 11 '22 19:11

AKKAweb


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

like image 44
mark Avatar answered Nov 11 '22 18:11

mark


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

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

like image 24
user1105491 Avatar answered Nov 11 '22 20:11

user1105491


Using saveField:

<?php

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

?>
like image 1
Andrew Senner Avatar answered Nov 11 '22 18:11

Andrew Senner