ravindar.dev
ravindar.dev

Reputation: 114

Update a row by 1 in CakePHP

I have searched for this question and found many similar answers like this one

Update a row +1 in CakePHP

and this is what the accepted answer looks like

$this->Widget->updateAll(

      array('Widget.numberfield' => 'Widget.numberfield + 1'),

      array('Widget.id' => 1)

);

Now iam using this query in cakephp3. Here is what mine looks like

$Questions=$this->loadModel('Questions');

$Questions->updateAll(

       array('questions.trend' => 'questions.trend + 1'),

       array('questions.description' => $undashed_title)

);

Every thing is working fine and query's are executing but when i check debugger for sql log, Here's what i found

UPDATE questions SET questions.trend = 'questions.trend + 1' WHERE questions.description = 'What type'

But my value in database is not updating like it should be (Iam saying this beacuse i also have copied this query on phpmyadmin console and its not working )

I believe the query should look like this

UPDATE questions SET questions.trend = questions.trend+1 WHERE questions.description = 'What Type'

Any help would be appreciated ,Thanks :)

Upvotes: 1

Views: 1057

Answers (1)

Well, as i said on comments, CakePHP 3 diverge a value from a expression, and the increment thing that you trying to do is a expression, to solve your "problem" you shall dig deep on CakePHP docs, and so you will find this http://book.cakephp.org/3.0/en/orm/saving-data.html#bulk-updates, yeah, right what you want. So, it becomes:

// load your beloved model
$questions = $this->loadModel('Questions');
// create a beauty expression
$expression = new QueryExpression('questions.trend + 1');
// execute a update with the beauty expression
$questions->updateAll(
   array('questions.trend' => $expression),
   array('questions.description' => $undashed_title)
);

And don't forget to load QueryExpression's namespace with use Cake\Database\Expression\QueryExpression;.

Yes, this is the wrong way to do on CakePHP 3, you shall the CakePHP's ORM, and move the increment thing to the model layer.

Upvotes: 5

Related Questions