简体   繁体   中英

cakePHP update table fields

I have a cakePHP problem - I want to make a update query like this

UPDATE table SET field = field + some_var

and I don't know how to do it...

Can anyone help me?

The only "right" way would be using cake's "atomic query" wrapper methods. In your case that would be "updateAll". The question is a complete duplicate of a dozen other questions - like Incrementing Cakephp database field by a value

$var = 1;
$this->Article->updateAll(
    array('Article.viewed' => 'Article.viewed + ' . $var),                    
    array('Article.id' => $id)
);

This is also in the docs: http://book.cakephp.org/2.0/en/models/saving-your-data.html#model-updateall-array-fields-array-conditions

There are two ways to do an update:

If you are only updating one field you can do:

$this->Model->id = foo;
$this->Model->saveField('field_name', 'field_value');

or, you can do an update using $this->Model->save():

$data = array(
    'Model'=>array(
        'id'=>foo,
        'field_name'=>'field_value',
        'another_field_name'=>'another_field_value'
    )
);

$this->Model->save($data);

You want to avoid using $this->Model->query() and use CakePHP's built in methods because the build in methods are datasource agnostic (they work the same on MySQL, Oracle, MSSQL etc.)

You can use the callback method beforeSave to implement what you need.

Callback Method: BeforeSave

public function beforeSave($options = array()) {
    if (!empty($this->data['table']['field'])){
         $this->data['table']['field'] += $this->data['table']['some_var'];
    }
    return true;
}

I think the best method is using the Model::updateAll(array $fields, array $conditions) .

The Model::saveField(string $fieldName, string $fieldValue, $validate = false) this method when you try to update using same primary key it shows cannot replace duplicate key error . And think when one updates they must be using the primary key as a matching value to update value.

Use

$this->Baker->updateAll(
    array('Baker.approved' => 'Baker.approved + ' . $some_var),
    array('Baker.id' => $someId)
);

For more information see: http://book.cakephp.org/2.0/en/models/saving-your-data.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM