MySQL表中的列名为"updated_at"。它是datetime类型,不是null。时间类型也是datetime。
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类型(因为它们是正确的)的情况下设置正确的值持久化?
两个选项。使用我在评论中提到的timestamable。对于symfony,它集成在StofDoctrineExtensionsBundle中。然后,您只需将其添加到映射yaml中,就不需要在控制器、服务等中添加其他代码。
选项二:将updated_at
设置为NULL而不是NOT NULL。NOT NULL表示,必须有一个值(例如,至少0000-00-00)。如果你在MySQL中允许NULL值,你将达到你所认为的。
原则不能跳过列,使用您在元数据配置中定义的所有字段。
你应该在构造函数中设置一些默认值,空字符串几乎适用于所有类型。
在持久化时只使用一次,后续的提取不会触发构造