Doctrine - Add default time stamp to entity like NOW()(Doctrine - 向实体添加默认时间戳,如 NOW())
问题描述
遵循 Doctrine 指南,我了解如何为实体设置默认值,但如果我想要日期/时间戳怎么办?
Following the Doctrine guidelines I understand how to set a default value for an Entity, but what if I wanted a date/time stamp?
- http://docs.doctrine-project.org/projects/doctrine-orm/en/2.1/reference/faq.html
我的问题是我的数据库在一个字段上有一个默认值 NOW() 但是当我使用 Doctrine 插入记录时,值是空或空白,但插入的其余部分发生了.
My problem is my database has a default of NOW() on a field but when I use Doctrine to insert a record the values are null or blank but the rest of the insert happened.
此外,由于 Doctrine 说要将默认值声明为常量,这也会产生问题.
Also since Doctrine says to declare the default as a const, this also creates a problem.
建议?
推荐答案
好的,我找到了解决方案:
Ok I found the solution:
- https://doctrine-orm.readthedocs.org/en/latest/reference/php-mapping.html?highlight=callback
- http://doctrine-orm.readthedocs.org/en/latest/reference/events.html#lifecycle-events
prePersist
选项就是我正在做的.
The prePersist
option is what I'm doing.
确保在注释中定义
<?php
/** @Entity
* @HasLifecycleCallbacks
*/
class User
这是他们提供的功能示例
and here is the function example they offer
/**
* @PrePersist
*/
public function doStuffOnPrePersist()
{
$this->createdAt = date('Y-m-d H:i:s');
}
如果你像我一样使用 ORM
And if you're using ORM like I am
<?php
/** @ORMEntity
* @ORMHasLifecycleCallbacks
*/
class User
这是他们提供的功能示例
and here is the function example they offer
/**
* @ORMPrePersist
*/
public function doStuffOnPrePersist()
{
$this->createdAt = date('Y-m-d H:i:s');
}
这篇关于Doctrine - 向实体添加默认时间戳,如 NOW()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Doctrine - 向实体添加默认时间戳,如 NOW()


基础教程推荐
- 如何替换eregi() 2022-01-01
- PHP PDO MySQL 查询 LIKE ->多个关键词 2021-01-01
- 如何在 Laravel 中使用 React Router? 2022-01-01
- 学说 dbal querybuilder 作为准备好的语句 2022-01-01
- YouTube API v3 点赞视频,但计数器不增加 2022-01-01
- 如何在 Laravel 5.3 注册中添加动态下拉列表列? 2021-01-01
- PHP 类:全局变量作为类中的属性 2021-01-01
- Cron Jobs 调用带有变量的 PHP 脚本 2022-01-01
- 在PHP中根据W3C规范Unicode 2022-01-01
- 有什么方法可以用编码 UTF-8 而不是 Unicode 返回 PHP`json_encode`? 2021-01-01