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

Database updates history

Hello, was just wandering what is the best way to support database history using the phalcon model? What I mean is instead of updating an record in a database I would like to flag it as removed and insert a new one. Cheers

I don't think anything like that is built in to Phalcon. You'll have to overwrite your model's update() and/or save() methods to have this behaviour.

that was my worry, anyway, thank you

Whatever you're updating, be sure it doesn't contain any keys used in relationships. For example, if you have a User with an auto incremented id (the key), name, email address, and office number - put the name, email address and office number in their own table, referencing the User record by user id. That way, any other table relationships that rely on the user's id number don't have to be updated when you generate a new entry because someone updated their email address.

that's exactly what I need for :) and blame :D

that's exactly what I need for :) and blame :D

You mean audit purpose?

that's exactly what I need for :) and blame :D

You mean audit purpose?

Yes, exactly and a possibility to recover mistakenly removed/updated data

edited Jan '20

tl;dr here is a simple example

/**
 * @mixin \Phalcon\Mvc\Model
 */
trait PhalconModelHistory
{
    protected function getChangedValuesAfterUpdate() : array
    {
        // I'm using getUpdatedFields() because this method will be called in afterUpdate()
        // One can use getChangedFields() to get the changes made before the save.
        $changes = [];
        foreach ($this->getUpdatedFields() ?? [] as $changedField) {
            $changes[$changedField] = ['to' => $this->$changedField];
        }

        return $changes;
    }
}

usage

class SomeModel extends Model
{
    use PhalconModelHistory;

    public function afterUpdate() : void
    {
        die(var_dump($this->getChangedValuesAfterUpdate()));
    }
}