Solved thread

This post is marked as solved. If you think the information contained on this thread must be part of the official documentation, please contribute submitting a pull request to its repository.

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.4k
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? http://docs.phalconphp.com/en/latest/reference/models.html#using-traits-as-behaviors