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

Object ID after object instantiation

$object = new Objects();

echo $object->id;

Why is this returning nothing? ID is auto increment value, defined as public variable. I can use $object->id after i save() the object, but why not right after i instantiated new object?



26.3k
Accepted
answer
edited Sep '14

id value is the value taken from a database. If the record is not saved in a database it has no ID yet. At the moment you have instantiated the object but not decided to save it in a DB. At this moment query like INSERT INTO... have NOT been made yet.

Only when you decide to save() it, then Phalcon will fire INSERT INTO... query. DB will create a new record and pass the ID back to Phalcon. Then you will be able to get the ID from the object.



17.0k
edited Sep '14

Makes perfect sense....



17.0k
edited Sep '14

Why is this not working either, in model?

public function afterCreate() {

$this->object_photo0 = $this->id;

}



26.3k

Could you provide the code of your model and controller?