在Doctrine中,updated_at,created_at的自动值 [英] Automatic values for updated_at, created_at in Doctrine
问题描述
我想在我的 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?
推荐答案
- 您可以调用
$ this-> setCreatedAt(new \DateTime())
使用__ construct
方法。 - 您可以使用生命周期回调
- You can call
$this->setCreatedAt(new \DateTime())
in__construct
method. - 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屋!