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.

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();


3.0k
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.