php Doctrine 中 updated_at、created_at 的自动值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17321893/
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 12:41:18  来源:igfitidea点击:

Automatic values for updated_at, created_at in Doctrine

phpdoctrine-orm

提问by Dmitry

I want to make fields updated_atand created_atin my Doctrine entitiesto update automatically.

我想让字段updated_atcreated_at我的Doctrine 实体自动更新。

In Ruby on Rails models there are 2 fields: updated_atand created_at.

在 Ruby on Rails 模型中,有 2 个字段:updated_atcreated_at.

Description can be found here: http://guides.rubyonrails.org/migrations.html#migration-overview:

可以在此处找到说明:http: //guides.rubyonrails.org/migrations.html#migration-overview

The timestamps macro adds two columns, created_at and updated_at. These special columns are automatically managed by Active Record if they exist.

时间戳宏添加了两列,created_at 和 updated_at。如果这些特殊列存在,Active Record 会自动管理它们。

Can I enable similar functionality in Doctrine 2?

我可以在 Doctrine 2 中启用类似的功能吗?

回答by oroshnivskyy

  1. You can call $this->setCreatedAt(new \DateTime())in __constructmethod.
  2. You can use Life Cycle Callbacks
  1. 您可以$this->setCreatedAt(new \DateTime())__construct方法中调用。
  2. 您可以使用生命周期回调
/**
 * @ORM\PrePersist
 * @ORM\PreUpdate
*/
public function updatedTimestamps(): void
{
    $this->setUpdatedAt(new \DateTime('now'));    
    if ($this->getCreatedAt() === null) {
        $this->setCreatedAt(new \DateTime('now'));
    }
}

And don't forget to add into entity class notation: @ORM\HasLifecycleCallbacks

并且不要忘记添加到实体类符号中: @ORM\HasLifecycleCallbacks

回答by BentCoder

This is another option if you would ever want to handle them separately.

如果您想单独处理它们,这是另一种选择。

use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity
 * @ORM\Table(name="person")
 * @ORM\HasLifecycleCallbacks
 */
class Person
{
    ..........

    /**
     * @var datetime $created
     *
     * @ORM\Column(type="datetime")
     */
    protected $created;

    /**
     * @var datetime $updated
     * 
     * @ORM\Column(type="datetime", nullable = true)
     */
    protected $updated;


    /**
     * Gets triggered only on insert

     * @ORM\PrePersist
     */
    public function onPrePersist()
    {
        $this->created = new \DateTime("now");
    }

    /**
     * Gets triggered every time on update

     * @ORM\PreUpdate
     */
    public function onPreUpdate()
    {
        $this->updated = new \DateTime("now");
    }

    ..........
}

回答by S?awomir Kania

The most convinient solution for me is Timestampablefeature of StofDoctrineExtensionsBundle.

对我来说最方便的解决方案是StofDoctrineExtensionsBundle 的Timestampable功能。

Simple configuration and later you are able to make fields createdAtand updatedAtof Entityfilled out automatically by adding two simple annotationslike:

简单的配置,以后你能够做出领域createdAtupdatedAtEntity填写了加入两个简单的自动annotations,如:

@Gedmo\Mapping\Annotation\Timestampable(on="create")

@Gedmo\Mapping\Annotation\Timestampable(on="create")

and/or

和/或

@Gedmo\Mapping\Annotation\Timestampable(on="update")

@Gedmo\Mapping\Annotation\Timestampable(on="update")

e.g.

例如

/**
 * @var \DateTime
 * @Gedmo\Mapping\Annotation\Timestampable(on="create")
 * @Doctrine\ORM\Mapping\Column(type="datetime")
 */
protected $createdAt;

/**
 * @var \DateTime
 * @Gedmo\Mapping\Annotation\Timestampable(on="update")
 * @Doctrine\ORM\Mapping\Column(type="datetime")
 */
protected $updatedAt;

Without any redundant code in pure PHP.

PHP.

回答by fdor

You can implement it as a trait as well - like this:

您也可以将其实现为特征 - 如下所示:

<?php

namespace App\Entity\Traits;

use DateTime;
use DateTimeInterface;
use Exception;

/**
 * Trait TimeStampableTrait
 * @package App\Entity\Trait
 */
trait TimeStampableTrait
{
    /**
     * @ORM\Column(type="datetime")
     */
    private $createdAt;

    /**
     * @ORM\Column(type="datetime")
     */
    private $updatedAt;

    /**
     * @return DateTimeInterface|null
     * @throws Exception
     */
    public function getCreatedAt(): ?DateTimeInterface
    {
        return $this->createdAt ?? new DateTime();
    }

    /**
     * @param DateTimeInterface $createdAt
     * @return $this
     */
    public function setCreatedAt(DateTimeInterface $createdAt): self
    {
        $this->createdAt = $createdAt;

        return $this;
    }

    /**
     * @return DateTimeInterface|null
     */
    public function getUpdatedAt(): ?DateTimeInterface
    {
        return $this->updatedAt ?? new DateTime();
    }

    /**
     * @param DateTimeInterface $updatedAt
     * @return $this
     */
    public function setUpdatedAt(DateTimeInterface $updatedAt): self
    {
        $this->updatedAt = $updatedAt;

        return $this;
    }

    /**
     * @ORM\PrePersist()
     * @ORM\PreUpdate()
     */
    public function updateTimestamps(): void
    {
        $now = new DateTime();
        $this->setUpdatedAt($now);
        if ($this->getId() === null) {
            $this->setCreatedAt($now);
        }
    }
}

Add this trait to your entity (and don't forget @ORM\HasLifecycleCallbacks()notation):

将此特征添加到您的实体(不要忘记@ORM\HasLifecycleCallbacks()符号):

<?php

namespace App\Entity;

use App\Entity\Traits\TimeStampableTrait;
use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity(repositoryClass="App\Repository\MyEntityRepository")
 * @ORM\HasLifecycleCallbacks()
 */
class MyEntity
{
    use TimeStampableTrait;
}