CakePHP: INSERT vs. UPDATE
olav — Fri, 07/22/2011 - 13:57
This has bitten me in the past.
My idiom for saving a record was
$data = array('title' => 'My article');
if ($id = $this->Post->field('id', $data)) {
$this->Post->create(array('id' => $id));
}
else {
$this->Post->create();
}
$this->Post->save($data + array('body' => 'I am the elaborate discurs');
This is correct only as long as the schema for the posts table does not define any default values. However, if it does, create() will initialize the affected fields with their default values. The following save() will happily overwrite these fields with their default values if they are not included in the data array.
The correct way to write this is
$data = array('title' => 'My article');
if ($id = $this->Post->field('id', $data)) {
$this->Post->id = $id;
}
$this->Post->create(FALSE);
$this->Post->save($data + array('body' => 'I am the elaborate discurs');
The FALSE parameter to create() prevents it from initializing fields with the default values from the schema. You can read this up in "the manual":http://book.cakephp.org/view/1031/Saving-Your-Data. Search for "Creating or updating".




Kommentiert
1 week 3 days ago
5 weeks 5 days ago
26 weeks 16 hours ago
27 weeks 4 days ago
27 weeks 5 days ago
31 weeks 3 days ago
1 year 11 weeks ago
1 year 34 weeks ago
1 year 42 weeks ago
2 years 1 week ago