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

Auto-insert current timestamp in model on create

Assume I want to save in DB the registration time of user.


CREATE TABLE user
(
    id INT UNSIGNED PRIMARY KEY NOT NULL AUTO_INCREMENT,
    email VARCHAR(255) NOT NULL,
    createdDate TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
);

Why it does not work?

<?php
// model
class User extends \Phalcon\Mvc\Model
{

    /**
     *
     * @var integer
     */
    public $id;

    /**
     *
     * @var string
     */
    public $email;

    /**
     * @var string
     */
    public $createdDate;
...

}

// controller
        $userA = new \Auth\Models\User();
        $userA->email = '[email protected]';
        $result = $userA->create();

        // why result === false and user is not saved?

if I remove $createdDate field from here and from DB - all is working correctly, user saved.



17.1k
Accepted
answer

Use

public function initialize() {
    $this->skipAttributesOnCreate(array("createdDate"));
}

For Skipping Null Values or Fields that uses default values

Are you using Phalcon 2.0.4?

I'm on 2.0.0. Sorry, I have added $this->skipAttributes(array('createdDate')); on another model that I have tested.