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

Update is changing not changed fields

Hi all.

I already have this on my model:

public function initialize() {
    $this->useDynamicUpdate( true );
}

I'm running this:

$row = new Models\Admins();
$row->setId( 1 );
$row->setName( 'test' );
$row->setEmail( '[email protected]' );
$row->save();

And for some reason, my database is receiving this:

UPDATE admins SET name = 'test', email = '[email protected]', password = null, created = null, modified = null WHERE id = 1

I don't want to change the password! Anyone knows why is this happening?

Thanks!

Note: I'm using Phalcon 2.0.0.



4.7k

What you want is Dynamic Update

As pointet in the Documentation:

SQL UPDATE statements are by default created with every column defined in the model (full all-field SQL update). You can change specific models to make dynamic updates, in this case, just the fields that had changed are used to create the final SQL statement.

So you need to set this in your Entity. I have a BaseEntity Class in my Projects that is extended by every other Entity.

public function initialize()
{
    /**
    * Use only the updated fields
    * @see https://docs.phalcon.io/en/latest/reference/models.html#dynamic-update
    */
    $this->useDynamicUpdate(true);
}

As I already said, I am using this feature.



473

In example above I see you create item not update item, if you want to update a item, i think such as example below


    $auth = $this->session->get('auth');
        if (!$auth) {
            $this->flashSession->error('You must be logged first');
            return $this->indexRedirect();
        }
        $parameters = [
            "id = ?0 AND (usersId = ?1 OR 'Y' = ?2 OR 'Y' = ?3)",
            "bind" => [$id, $auth['id'], $auth['moderator'], $auth['admin']]
        ];
        if (!$object = Posts::findFirst($parameters)) {
            $this->flashSession->error(t('Post doesn\'t exist.'));

            return $this->indexRedirect();
        }
        $object->setEmail('[email protected]');
        $object->save()