How to handle default datetime values in doctrine entities?
I’m working with the following code:
#[Entity]
#[Table(name: 'messages')]
class Message
{
#[Column(name: 'sent_at', type: Types::DATETIME_IMMUTABLE, updatable: false, options: ['default' => 'CURRENT_TIMESTAMP'])]
private readonly DateTimeImmutable $sent_at;
...
}
and orm:schema-tool:create --dump-sql
seems to produce proper SQL
CREATE TABLE messages (
id int unsigned AUTO_INCREMENT NOT NULL,
sent_at datetime DEFAULT CURRENT_TIMESTAMP NOT NULL,
message text NOT NULL,
PRIMARY KEY (id)
);
but when I try to create such entity without manually setting sent_at
(expecting it to use the default current timestamp)
$message = new Message($message);
$this->entity_manager->persist($message);
$this->entity_manager->flush();
I get this error:
Uncaught PDOException: SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'sent_at' cannot be null in vendor/doctrine/dbal/src/Driver/PDO/Statement.php:55
What is causing this error, and how can I correctly set a default timestamp value for sent_at in Doctrine?
I’d like to avoid manually setting sent_at
in the constructor if possible.
"doctrine/orm": "^3.0",
"doctrine/dbal": "^4.0",
You need to sign in to view this answers