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()


- 如何使用 Google API 在团队云端硬盘中创建文件夹? 2022-01-01
- PHP foreach() 与数组中的数组? 2022-01-01
- openssl_digest vs hash vs hash_hmac?盐与盐的区别HMAC? 2022-01-01
- Oracle 即时客户端 DYLD_LIBRARY_PATH 错误 2022-01-01
- 使用 GD 和 libjpeg 支持编译 PHP 2022-01-01
- 覆盖 Magento 社区模块控制器的问题 2022-01-01
- 如何在 Symfony2 中正确使用 webSockets 2021-01-01
- Laravel 5:Model.php 中的 MassAssignmentException 2021-01-01
- PHP - if 语句中的倒序 2021-01-01
- 如何从数据库中获取数据以在 laravel 中查看页面? 2022-01-01