Reputation: 797
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?
Upvotes: 1
Views: 9370
Reputation: 1623
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
Upvotes: 0
Reputation: 284
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.
Upvotes: 0
Reputation: 21743
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
Upvotes: 7
Reputation: 4313
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.)
Upvotes: 4
Reputation: 61
You can use the callback method beforeSave to implement what you need.
public function beforeSave($options = array()) {
if (!empty($this->data['table']['field'])){
$this->data['table']['field'] += $this->data['table']['some_var'];
}
return true;
}
Upvotes: 0