在Doctrine中,updated_at,created_at的自动值 [英] Automatic values for updated_at, created_at in Doctrine

查看:121
本文介绍了在Doctrine中,updated_at,created_at的自动值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在我的 Doctrine实体中对字段 updated_at created_at 进行更新

I want to make fields updated_at and created_at in my Doctrine entities to update automatically.

在Ruby on Rails模型中,有2个字段: updated_at created_at

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

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

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


timestamps宏添加两列,created_at和updated_at。这些特殊列(如果存在)由Active Record自动管理。

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

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

Can I enable similar functionality in Doctrine 2?

推荐答案


  1. 您可以调用 $ this-> setCreatedAt(new \DateTime()) 使用 __ construct 方法。

  2. 您可以使用生命周期回调

  1. You can call $this->setCreatedAt(new \DateTime()) in __construct method.
  2. You can use Life Cycle Callbacks



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

不要忘了添加实体类符号:
@ ORM\HasLifecycleCallbacks

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

这篇关于在Doctrine中,updated_at,created_at的自动值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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