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

MySQL default values and double save()

Hi everyone! And sorry for my english.

I have table with some integer fields NULL DEFAULT '0' and I have this php code on phalcon v2.0.3:

$robot = new Robots();
$robot->email = $this->request->getPost('email', 'email');
$robot->ip = $this->request->getClientAddress(true);
...
//I skip fields with default values
...

if ($robot->save()) { //after this save() skipped fields have value 0, all right 
    if ($this->request->hasFiles(true)) {
        foreach ($this->request->getUploadedFiles(true) as $file) {
            ...
        }

        if ($robot->image_id == 0) {
            $robot->image_id = $images->id;
            $robot->save(); //but after this save() skipped fields have value NULL, why?
        }
    }
}

I tried

$this->useDynamicUpdate(true);

but it's not help me, I tried annotations, but it's not help me.

If i use

$robot2 = Robots::findFirst($robot->id);
$robot2->image_id = $images->id;
$robot2->save()

instead of second

$robot->save();

all right.

You have to reload the record after the first save to it will recover the default values from the database:

$robot->reload();

why don't you just save at the end instead of doing an insert and then an update?

You have to reload the record after the first save to it will recover the default values from the database:

With this line I get

The method 'reload' doesn't exist on model 'MyProject\MyModule\Models\Robots'

why don't you just save at the end instead of doing an insert and then an update?

Because I have to get $robot->id before saving images.



98.9k
Accepted
answer

It must be $robot->refresh();

It must be $robot->refresh();

Thank you, it solved my problem.