开发者

Update a row +1 in CakePHP

开发者 https://www.devze.com 2023-02-06 11:55 出处:网络
I am trying to update a r开发者_运维技巧ow in the database but haven\'t found a way to do this in the CakePHP way (unless I query the row to retrieve and update).

I am trying to update a r开发者_运维技巧ow in the database but haven't found a way to do this in the CakePHP way (unless I query the row to retrieve and update).

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

In CodeIgniter, it would have been as simple as:

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

How do I do this without querying the row first, retrieve the value, then updating the row with the information I got?


I don't think CakePHP has a similar method for doing this in a normal save() on a single row.

But the updateAll() method, which updates multiple rows, does support SQL snippets like so:

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

The first param is an array of fields/values to be updated, and the second param are the conditions for which rows to update.

Apart from that I think the only thing is to use:

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

Which lets you query with raw SQL. [EDIT: but this is not recommended as it bypasses the ORM.]


Try this

<?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( ));
        }
    }
?>

Basically you are passing the id, if it exists you read the Widget model (see the notes above, null as 1st param read the entire table) and then you are using Model::set to st the field to a value one greater than itself - remember to cast to int if you store the field as a char/varchar - and then save the model.

0

精彩评论

暂无评论...
验证码 换一张
取 消