We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

get model id (not auto_increment) after save

Hello, I am having trouble retrieving the model's id after I save the model when I am not using auto_increment in my SQL.

public function beforeValidationOnCreate() {
    $this->uuid = new RawValue('UUID()');
}

//in the controller
if($model->validation()) {
  $model->save();
  echo $model->uuid;
}

The result is i get is 'UUID()' (without the quotes). The Database gets the value correctly. Its just I can't retrieve it in the application right after save.

Thanks in advance, Gasim



98.9k

Identity columns are automatically updated using lastInsertId https://php.net/manual/en/pdo.lastinsertid.php, this is not the case because the key is not an auto increment column or a sequence, so the ORM can't automatically obtain the value from the column using that function. You can "reload" the entity to refresh the values after create the record:

<?php

class Robots extends Phalcon\Mvc\Model
{
    public function afterSave()
    {
        $this->refresh();
    }
}


8.7k

the refresh didn't work. because How is it suppose to know what the ID is if it doesn't really hold the value for that ID?



98.9k

You're right, then I don't think there is a way to obtain the UUID value since the ORM does not have a clue about the record created, I would set up the UUID using a PHP function, so the model will have the real value and you don't need to reload it: https://github.com/ramsey/uuid