kurisukun
kurisukun

Reputation: 3159

CakePHP iterate through all rows in the DB and update?

I am not sure of the cakephp way to do this. My model looks like below (simplified)

Model
id      column1    column2    column3     sum
1232       3           5          2
5474       5           10         4

Now, because of the nature of the program, I need to iterate through the database, multiply each column value by a multiplier, then sum those values, then put that value into each record's sum. So, for example, if I had a variable $multiplier = 2, then I would want to have this happen for the first row:

(3*$multiplier) + (5*$multiplier) + (2*$multiplier) = 20


Model
id      column1      column2   column3     sum
1232       3           5          2         20
5474       5           10         4         38

Of course, this is very simplified, but it's representative of what I want to do.

Is there a cakephp way to do this? I dont have an auto-incrementing id column in the db, but rather just an id column (which is unique).

Thank you!

Upvotes: 0

Views: 561

Answers (1)

deceze
deceze

Reputation: 522081

Let the database do it for you:

$this->Model->updateAll(array('sum' => 'column1 + column2 + column3'));

http://book.cakephp.org/view/1031/Saving-Your-Data (see section updateAll).

Upvotes: 1

Related Questions