php Doctrine - 向实体添加默认时间戳,如 NOW()

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13850693/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 06:09:36  来源:igfitidea点击:

Doctrine - Add default time stamp to entity like NOW()

phppostgresqlsymfonydoctrine-ormentities

提问by Phill Pafford

Following the Doctrine guidelines I understand how to set a default value for an Entity, but what if I wanted a date/time stamp?

遵循 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.

我的问题是我的数据库在一个字段上有一个默认值 NOW() 但是当我使用 Doctrine 插入记录时,值是空或空白,但插入的其余部分发生了。

Also since Doctrine says to declare the default as a const, this also creates a problem.

此外,由于 Doctrine 说要将默认值声明为 const,这也会产生问题。

Suggestions?

建议?

回答by Phill Pafford

Ok I found the solution:

好的,我找到了解决方案:

The prePersistoption is what I'm doing.

prePersist选项是我在做什么。

Make sure you define in the annotations

确保您在注释中定义

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

And if you're using ORM like I am

如果你像我一样使用 ORM

<?php

/** @ORM\Entity 
 *  @ORM\HasLifecycleCallbacks 
 */
class User

and here is the function example they offer

这是他们提供的功能示例

/** 
 *  @ORM\PrePersist 
 */
public function doStuffOnPrePersist()
{
    $this->createdAt = date('Y-m-d H:i:s');
}

回答by David Baucum

In my experience it is best to put everything in your Entities and not try to force your database to bypass the ORM.

根据我的经验,最好将所有内容都放在您的实体中,而不是试图强制您的数据库绕过 ORM。

<?php
namespace Phill\PaffordBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
 * Stack
 * @ORM\Table()
 */
class Stack
{
  /**
   * @var integer
   * @ORM\Column(type="integer")
   * @ORM\Id
   * @ORM\GeneratedValue(strategy="AUTO")
   */
  private $id;

  /**
   * @var \DateTime
   * @ORM\Column(type="datetime")
   */
  private $startDate;

  public function __construct()
  {
    $this->startDate = new \DateTime();
  }

}

回答by Alexandre

In order to have exactly NOW()you could extend Doctrine\DBAL\Types\DateTimeType.

为了准确地NOW()你可以扩展Doctrine\DBAL\Types\DateTimeType.

Other method:

其他方法:

class DateTimeNow
{
    public function format() 
    {
        return 'NOW()';
    }
}

Then you can use $entity->setFieldDatetime(DateTimeNow())instead of $entity->setFieldDatetime(new Datetime()).
Note: The method format()is automatically called by Doctrine.

然后你可以使用$entity->setFieldDatetime(DateTimeNow())代替$entity->setFieldDatetime(new Datetime())
注意:该方法format()由 Doctrine 自动调用。

回答by Dennis

Try this:

尝试这个:

/**
 * @var \DateTime
 *
 * @Column(name="created", type="datetime", nullable=false)
 */
private $created;

function __construct()
{
    $this->created = new \DateTime();
}

The whatever $valueyou assign to createdfield, has to be able to handle this call:

$value您分配给created字段的任何内容都必须能够处理此调用:

$value->format('Y-m-d H:i:s');

See relevant Doctrine code line

查看相关的Doctrine代码行

Tested to work with Doctrine 2.5.4

经测试可与 Doctrine 2.5.4 一起使用

Note: above works at creation time but not on update by default -- you have to manually set createdproperty to new \DateTime()when you do an update or look into doStuffOnPrePersist

注意:以上在创建时有效,但默认情况下不在更新时-您必须在进行更新或查看时手动将created属性设置new \DateTime()doStuffOnPrePersist

/** @PrePersist */
public function doStuffOnPrePersist()
{
    $this->created = date('Y-m-d H:i:s');
}

回答by Tuncay Elvana?a?

You can use TimestampableEntity Trait for automatically create created_at and updated_at fields in you Entity;

您可以使用 TimestampableEntity Trait 在您的实体中自动创建 created_at 和 updated_at 字段;

First install doctrine-extensions;

首先安装学说扩展;

composer require gedmo/doctrine-extensions

Secondly add trait into your Entity Class;

其次将特征添加到您的实体类中;

use Gedmo\Timestampable\Traits\TimestampableEntity;

    /**
     * @ORM\Entity(repositoryClass="App\Repository\ProjectRepository")
     */
    class Project
    {
        use TimestampableEntity;

回答by Mike Brant

For PostgreSQL, you should just be able to pass string value of nowfor the field to get the timestamp to function.

对于 PostgreSQL,您应该能够传递now该字段的字符串值以获取时间戳功能。