Doctrine中的updated_at,created_at的自动值

Dmi*_*try 38 php doctrine-orm

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

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

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

时间戳宏添加了两列,created_at和updated_at.这些特殊列由Active Record自动管理(如果存在).

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

小智 93

  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'));
    }
}
Run Code Online (Sandbox Code Playgroud)

并且不要忘记添加到实体类表示法中: @ORM\HasLifecycleCallbacks

  • 在此处获取OOP示例-https://gist.github.com/lelledaniele/be67e03b51e04ab9f9b04b985ccd94e2 (2认同)

Ben*_*der 58

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

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

    ..........
}
Run Code Online (Sandbox Code Playgroud)

  • @El_Matella 您只需更改 `onPrePersist()` 函数,以便它同时设置 `created` 和 `updated`。如果您之前在生产中也没有这样做,则可以轻松地在数据库中修复。 (2认同)
  • 非常好。对于未来的用户,不要忘记在类注释中添加 @ORM\HasLifecyleCallbacks (这会节省我一些时间)。 (2认同)

Sła*_*nia 12

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

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

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

和/或

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

例如

/**
 * @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;
Run Code Online (Sandbox Code Playgroud)

没有任何纯粹的冗余代码PHP.

  • 如果您已经使用 StofDoctrineExtensions(可能是我们大多数人),那么这是最好的解决方案。应该注意的是,您需要启用时间戳:https://symfony.com/doc/master/bundles/StofDoctrineExtensionsBundle/configuration.html#activate-the-extensions-you-want (4认同)

fdo*_*dor 6

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

<?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);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

将此特征添加到您的实体(不要忘记@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;
}
Run Code Online (Sandbox Code Playgroud)