Doctrine - 向实体添加默认时间戳,如 NOW() [英] Doctrine - Add default time stamp to entity like NOW()

查看:35
本文介绍了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?

我的问题是我的数据库在一个字段上有一个默认值 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:

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()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆