tags:

views:

152

answers:

2

I'm just getting familiar with cakephp (thanks to the developer before me), and ran into something funny. I have finally found out what went wrong, but still do not know why. In very pseudo code:

a controller function calls bar() twice in the same scope:

$value = 'A';
$this->foo->bar($value);
// do other stuff
$value = 'B';
$this->foo->bar($value);

bar() basically just calls cakephp's save() model to write $value to table foobar$:

$AppModel->save(array(
  'AppModel'=> array('value'=>$value)
));

I expected that save() would create two rows in foobar$, however this was not the case. It first created a row with value A, then updated that row to value B. When the second call ran, it recognized the DB id generated by the previous call, decided it was the same entry and made it an update instead of insert. It sort of makes sense, but they still are separate calls, right? What obvious thing am I missing here? Thanks a lot.

+4  A: 

After saving something to the database, Cake sets the $Model->id to the last insert id.

When saving, if there's either an id field in the data array it is supposed to save, or if there's an id set on $Model->id, Cake will update this entry instead. Both of these update the entry 42:

$Model->save(array('id' => 42, 'value' => 'foo'));

$Model->id = 42;
$Model->save(array('value' => 'foo'));

To make sure you're creating a new entry, call Model::create(), as described here.

deceze
+1  A: 

I typically always put a model create call before a save. If the array your saving has the primary key already it will update the row, otherwise it does an insert:

Insert:

$Model->create();
$Model->save(array('value'=>'foo'));

Update

$Model->create();
$Model->save(array('id'=>1,'value'=>bar'));
jsapara