[英]How to properly set entity update time with Doctrine?
MySQL表中的列称为“updated_at”。 它是datetime类型,不是null。 Doctine类型也是日期时间。
CREATE TABLE `example` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`created_at` datetime NOT NULL,
`updated_at` datetime NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
Some\Bundle\Entity\Example:
type: entity
table: examples
fields:
id:
id: true
type: integer
generator:
strategy: IDENTITY
...
createdAt:
type: datetime
column: created_at
updatedAt:
type: datetime
column: updated_at
$e = new Example;
$e->setCreatedAt(new \DateTime);
$em->persist($e);
/* after this I need $e->updatedAt to be MySQL's default 0 (0000-00-00) */
$em->flush();
/* but it will throw
"Integrity constraint violation: 1048 Column 'updated_at' cannot be null"
if I won't set it in Example::__contruct()
which I don't see any reason to do
apart from complying with Doctrine shortcomings. */
如果实体在创建后没有更新过,我不希望在此列中有任何值。
如何在不更改MySQL或Doctrine类型的情况下跳过此列或设置正确的值(因为它们是正确的)?
两种选择。 使用我在评论中提到的Timestampable 。 对于symfony,它集成在StofDoctrineExtensionsBundle中 。 然后,您只需将其添加到映射yaml中,并且不需要控制器,服务等中的其他代码。
选项二:将updated_at
设置为NULL而不是NOT NULL。 NOT NULL意味着,必须有一个值(例如至少为0000-00-00)。 如果在MySQL中允许NULL值,您将达到您的考虑范围。
Doctrine不能跳过列,使用您在元数据配置中定义的所有字段。
你应该在构造函数中设置一些默认值,空字符串适合几乎所有类型。
它只会持久使用一次,后续的提取不会触发构造。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.