简体   繁体   English

如何使用Doctrine正确设置实体更新时间?

[英]How to properly set entity update time with Doctrine?

Column in MySQL table is called "updated_at". MySQL表中的列称为“updated_at”。 It's of datetime type, not null. 它是datetime类型,不是null。 Doctine type is datetime as well. 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. */

If entity wasn't ever updated after it was created I don't want to have any value in this column. 如果实体在创建后没有更新过,我不希望在此列中有任何值。

How to skip this column or set proper value upon persist without changing MySQL or Doctrine types (because they are right)? 如何在不更改MySQL或Doctrine类型的情况下跳过此列或设置正确的值(因为它们是正确的)?

Two options. 两种选择。 Use the Timestampable as i mentioned in the comments. 使用我在评论中提到的Timestampable For symfony it's integrated in the StofDoctrineExtensionsBundle . 对于symfony,它集成在StofDoctrineExtensionsBundle中 Then you simply add it to your mapping yaml and no further code in controllers, services, etc. is required. 然后,您只需将其添加到映射yaml中,并且不需要控制器,服务等中的其他代码。

Option two: Set the updated_at to NULL instead of NOT NULL. 选项二:将updated_at设置为NULL而不是NOT NULL。 NOT NULL means, there must be a value (eg 0000-00-00 at least). NOT NULL意味着,必须有一个值(例如至少为0000-00-00)。 If you allow a NULL value in MySQL, you will reach what you consider. 如果在MySQL中允许NULL值,您将达到您的考虑范围。

Doctrine cannot skip columns, uses all fields which you defined in metadata config. Doctrine不能跳过列,使用您在元数据配置中定义的所有字段。

You should set some default value in constructor, empty string suits well for almost all types. 你应该在构造函数中设置一些默认值,空字符串适合几乎所有类型。

It will be used just once upon persist, subsequent fetches won't trigger construct. 它只会持久使用一次,后续的提取不会触发构造。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM