Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Will the save method in a Cakephp model class choose between creating and updating a record?

Tags:

php

cakephp

Basically, I want to achieve the same thing as ON DUPLICATE KEY in MySQL.

Here's a contrived example:

$rec = array('Foo' => array(
  'id' => 999,  // Assume there isn't already a record with this id
  'website' => 'google'
));
$this->Foo->save($rec);

// save with different 'website' value
$rec['Foo']['website'] = 'stackoverflow';
$this->Foo->save($rec);

Does the last line update the record that was created just a few lines up?

like image 500
allyourcode Avatar asked Nov 23 '25 21:11

allyourcode


1 Answers

If you call save(), supplying a record with an existing id (or whatever is the primary key), it will update, otherwise it will create a new record.

So in your case, yes, it would update the record that was first created at the top.

Update

Here's the supporting documentation:

Creating or updating is controlled by the model's id field. If $Model->id is set, the record with this primary key is updated. Otherwise a new record is created.

Under the documentation for Model::save().

like image 115
Peter Avatar answered Nov 25 '25 10:11

Peter



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!