user3337590
user3337590

Reputation: 160

How to update an existing record in CakePHP?

I am using CakePHP and following its tutorial. I want to update a record but when i do its create another record not updating. according to tutorial my code is given below

$data = array('Id' => $id, 'Approved' => 12);
$this->names->save($data);

it results in

SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry 4 for key PRIMARY

And if I do this

$this->names->Id=$id;

It adds a new record. How should I fix this ?

Upvotes: 7

Views: 27547

Answers (4)

Muhammad Ali Hassan
Muhammad Ali Hassan

Reputation: 962

$this->names->id=$id;                
$this->names->set(array('Approved'=>12));                
$this->names->save();

Upvotes: 14

user216084
user216084

Reputation:

To update a single field value when you have the primary key available, saveField() is also available.

Quoting from documentation:

Model::saveField(string $fieldName, string $fieldValue, $validate = false)

Used to save a single field value. Set the ID of the model ($this->ModelName->id = $id) just before calling saveField(). When using this method, $fieldName should only contain the name of the field, not the name of the model and field. For example, to update the title of a blog post, the call to saveField from a controller might look something like this:

$this->Post->saveField('title', 'A New Title for a New Day');

It also has facility for passing parameters like validate, callbacks etc using an alternate syntax:

saveField(string $fieldName, string $fieldValue, array $params = array())

References: Documentation, API

Upvotes: 2

Roberto Maldonado
Roberto Maldonado

Reputation: 1595

Unless you're intentionally not following Cake naming conventions (with a strong reason), you should stick to it. That means, models should be capitalized-singular named, and table fields should be lowercase. Also, your data array has to have the name of the model you want to save.

So:

$data = array('Name' => array('id' => $id, 'approved' => 12));
$this->Name->save($data);

Upvotes: 2

arilia
arilia

Reputation: 9398

The key must be id and not Id. If in your table you can't use id (lowercase) and you have to use Id (uppercase) then you have to set it in your Model file

also you are not followeing the conventions: the model should be Name and not names (singular and CamelCase)

Upvotes: 4

Related Questions