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

setting a default value for a datetime field in model

How can I set a default value for a field that maps to a MySQL DateTime field? I've tried time() and also new \DateTime() to no avail.

You can use Phalcon\Db\RawValue:

$robot = new Robot();
$robot->datetimecolumn= new \Phalcon\Db\RawValue("now()");
$robot->save();


5.1k
Accepted
answer
edited Aug '17

with date php function its works with all databases You can do it in model


<?php

namespace Store\Toys;

use Phalcon\Mvc\Model;

class RobotParts extends Model
{
    public $myDate = date("Y-m-d H:i:s"); 
}

Edit :

You can do it also in model before save


public function beforeCreate()
    {
        $this->created_at = date("Y-m-d H:i:s"); 
    }

    public function beforeUpdate()
    {
        $this->updated_at = date("Y-m-d H:i:s"); 
    }

Just wanted to point out that it's also possible to use behaviours and listen to the beforeCreate / beforeUpdate event, though this is a long-winded way of using the model's beforeCreate and beforeUpdate methods.

edited Aug '17

Consider an alternative to use timestamp as a "safer" data type when dealing with dates.

Interesting - I couldn't figure out how to set a default value for timestamp on mysql so I avoided it! But, I also found out that timestamp has some very interesting limits up to the year 2038 only which would have not been sufficient for me.

edited Aug '17

Indeed, YK38 bug. But only if you're dealing with insurance policies or something really long term, you could be affected. But hey - world might not be 'till then :)

I'll send you example how to set timestamp by default later as I'm running out of laptop batery ATM.