Could someone tell me how to add the default value on a DateTime column? I can't do it like this:
protected $registration_date = date("Y-m-d H:i:s", time());
So how can I handle it?
Learn MySQL from scratch for Data Science and Analytics We can set the now() function as a default value with the help of dynamic default. First, we will create a table with data type” datetime”. After that, we will set now() as the default value for column “MyTime” as shown below.
DATETIME has a default of NULL unless defined with the NOT NULL attribute, in which case the default is 0.
For default value CURRENT_TIMESTAMP:
@ORM\Column(name="created_at", type="datetime", options={"default": "CURRENT_TIMESTAMP"})
Or for older Symfony versions:
@ORM\Column(name="created_at", type="datetime", options={"default": 0})
Worked for me... However this works only with MySQL.
You map your property as DateTime type then set the value in the constructor using a new DateTime instance:
/**
* @Entity
* @Table(name="...")
*/
class MyEntity
{
/** @Column(type="datetime") */
protected $registration_date;
public function __construct()
{
$this->registration_date = new DateTime();
}
}
This works as the constructor of a persisted class is not called upon hydration.
You can also use lifecycle callbacks if you want to be very precise:
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\HasLifecycleCallbacks
* ...
*/
class MyEntity
{
/**
* @ORM\PrePersist
*/
public function onPrePersistSetRegistrationDate()
{
$this->registration_date = new \DateTime();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With