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.

How can I create a new record with orm only save several column like useDynamicUpdate does?

How can I create a new record with orm only save several column like useDynamicUpdate does?

table

id pk autoincrement
name varchar(20) not null

code

$model = new User();
$model->name = 'Hello';
$model->save();

What can I do if add a new column avatar, the code will go wrong, right? becase avatar can not be null.

Why phalcon have to add all column but what I wrote?

class User extends \Phalcon\Model
{
    public function beforeSave()
    {
        if(!$this->avatar) {
            $this->avatar = new \Phalcon\Db\RawValue('NULL');
            // or, to use the assigned default value from the DB:
            $this->avatar = new \Phalcon\Db\RawValue('DEFAULT');
        }
    }
}
edited Jul '18

Thank you bro.

But can this be done with every column? In fact, I prefered this can be accomplished below

$user = new User();
$user->user_id = '33bf9a1e807b11e886530800270ab995';
$user->create_time = time();
$user->save();

//phalcon
insert into user (user_id, name, create_time) values ('33bf9a1e807b11e886530800270ab995', NULL, 1530812727)

//expected
insert into user (user_id, name, create_time) values ('33bf9a1e807b11e886530800270ab995', default,1530812727)
class User extends \Phalcon\Model
{
  public function beforeSave()
  {
      if(!$this->avatar) {
          $this->avatar = new \Phalcon\Db\RawValue('NULL');
          // or, to use the assigned default value from the DB:
          $this->avatar = new \Phalcon\Db\RawValue('DEFAULT');
      }
  }
}


298
Accepted
answer

I found two way to approach this. source

  1. Put this to custom base model
public function beforeValidationOnCreate() {
  $metaData = $this->getModelsMetaData();
  $attributes = $metaData->getNotNullAttributes($this);

  // Set all not null fields to their default value.
  foreach($attributes as $field) {
      if(!isset($this->{$field}) || is_null($this->{$field})) {
          $this->{$field} = new RawValue('default');
      }
  }
}
  1. set the default value yourself.
public $sort = 0;
public $views = 0;