Update +1 line in CakePHP

I am trying to update a row in a database but have not found a way to do this in CakePHP method (unless I query the row to retrieve and update).

UPDATE mytable (field) VALUES (field+1) WHERE id = 1

In CodeIgniter, this would be as simple as:

$this->db->set('field', 'field+1', FALSE);
$this->db->where('id', 1);
$this->db->update('mytable');

How can I do this without querying the string first, get the value, and then update the string with the information I received?

+3
source share
2 answers

I don’t think CakePHP has a similar method for this in the usual save () on one line.

But the updateAll () method, which updates multiple rows, does support SQL fragments:

$this->Widget->updateAll(
    array('Widget.numberfield' => 'Widget.numberfield + 1'),
    array('Widget.id' => 1)
);

The first parameter is an array of updated fields / values, and the second parameter is the conditions for updating the rows.

Also, I think the only thing to use is:

$this->Widget->query('YOUR SQL QUERY HERE');

SQL. [EDIT: , ORM.]

+11

<?php
    class WidgetsController extends AppController {
        public function someFunction( $id = null ){
            if( $id ){

                // read all fields from the model
                // alternately you can $this->Widget->read( array( 'field' ), $id );
                $this->Widget->read( null, $id );

                // grab the 'field' field so we don't have to type out the data array
                $field = $this->Widget->data[ 'Widget' ][ 'field' ];

                // where field is the name of the field to be incremented
                $this->Widget->set( 'field', $field + 1 );
                $this->Widget->save( );
            }

            // someday cake devs will learn to spell referrer
            $this->redirect( $this->referer( ));
        }
    }
?>

id, , (. , null, 1- table), Model:: set, , , - int, char/varchar - .

+1

Source: https://habr.com/ru/post/1787746/


All Articles