I am trying to use Phalcons
save()
function to either create or update a record depending on whether the record is already in the database from here
I am doing the following:
$vars = $this->request->getPost();
$code = new Code();
$code->save( $vars, array("code_type", "code", "name") );
When I am sending an update to my controller, the "id" field has the primary key populated, whereas it is blank (but the array key still exists) if I am creating the record.
My understanding is that the ORM should either create or update the record depending on whether the primary key exists or not. The problem I am having is that it is always creating the record- not updating.
I've also tried something like the below, however the reverse is true, when I use find:
$code = Code::findFirst($vars["id"]);
$code->save( $vars, array("code_type", "code", "name") );
Any idea what I could be doing wrong? I want to get to a point where I have a single controller for my insert/update actions.
It's not surprising that the first example is only creating new records, because you're neither loading an existing record nor including the "id" in the white list of fields to save. Instantiating your object as follows should solve the problem (assuming the "id" is an integer):
$code = ($id = (int) $vars['id']) ? Code::findFirst($id) : new Code();