Jeffrey L. Roberts
Jeffrey L. Roberts

Reputation: 2994

Add One to Integer Column Using Query in CakePHP 3

I dont recall exactly how, but I do remember being able to add one to an integer column in mysql with a query without knowing the value of that integer column...

something like

update table set column=column+1 where id=1

I am wondering, how can I do the above query with CakePHP 3

Upvotes: 1

Views: 311

Answers (1)

ndm
ndm

Reputation: 60463

You can use \Cake\ORM\Table::updateAll() (or the underlying \Cake\Database\Query::update()), and use an expression to generate the arithmetic operation part, something like:

$additionExpression = $Table->query()->newExpr('column + 1');

$affectedRows = $Table->updateAll(
    ['column' => $additionExpression],
    ['id' => 1]
);

Or a little more complex in case you want to make use of automatic identifier quoting:

$additionExpression = $Table
    ->query()
    ->newExpr()
    ->add([
        new \Cake\Database\Expression\IdentifierExpression('column'),
        '1'
    ])
    ->setConjunction('+'); // tieWith() before CakePHP 3.4

See also

Upvotes: 2

Related Questions