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

Models - soft update

Hey,

for hours I'm trying to figure out how it is possible to create a soft update. What I mean is, how can I stop an update like this from overwriting columns that aren't even defined?

$ticket             = new Ticket();
$ticket->id         = $id;
$ticket->title      = $title;
$ticket->content    = $content;
$ticket->status     = "new";
$ticket->update()


6.9k
Accepted
answer

You can use a beforeValidationOnCreate method inside of your model like inside vokuros user model: https://github.com/phalcon/vokuro/blob/master/app/models/Users.php

Or if you are asking how to use your schemas default column value then you can use

public function beforeValidation() {
    $this->property = \Phalcon\Db\RawValue('default');
}


174

For global datetime updates on models I use this approach in BaseModel:

mysql> `created` datetime DEFAULT NULL, `updated` datetime DEFAULT NULL,
<?php 
class BaseModel extends \Phalcon\Mvc\Model
{
    public function initialize()
    {
        $this->addBehavior(
            new \Phalcon\Mvc\Model\Behavior\Timestampable([
                'beforeCreate' => [
                    'field' => 'created',
                    'format' => 'Y-m-d H:i:s',
                ],
                'beforeUpdate' => [
                    'field' => 'updated',
                    'format' => 'Y-m-d H:i:s',
                ],
            ])
        );
}

I like that you are using inheritance urulab - perhaps take it one step further and implement it as a trait so that all models can extend basemodel even if they arent timestampable? https://docs.phalcon.io/en/latest/reference/models.html#using-traits-as-behaviors