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');
}

相关文章