我的entity类中有一个带有@PreUpdate注释的方法,但它似乎只有在实体更新时才会被调用。插入新实体时不调用它。文档中提到了关于preUpdate事件:
“预更新事件发生在对实体数据执行数据库更新操作之前。”
/** * @PreUpdate * @PrePersist */ public function beforeSave() { if (!$this->getCreatedAt()) { $this->setCreatedAt(new \DateTime()); } $this->setModifiedAt(new \DateTime()); }
Persist和Update是两个不同的事件,因此如果希望回调同时应用于这两个事件,则需要两个注释。相反,创建两种方法可以满足您的疑虑:
/** * @PrePersist */ public function beforePersist() { $this->setCreatedAt(new \DateTime()); $this->setModifiedAt(new \DateTime()); } /** * @PreUpdate */ public function beforeUpdate() { $this->setModifiedAt(new \DateTime()); }