如何在Doctrine2 SELECT查询中处理DateTime类型的默认值?

Rey*_*rPM 5 php doctrine symfony doctrine-orm

我有以下Doctrine2实体:

<?php

use Doctrine\ORM\Mapping as ORM;
use Gedmo\Timestampable\Traits\TimestampableEntity;
/**
 * @ORM\Entity
 */
class Account
{
    use TimestampableEntity;

    /**
     * @var integer
     *
     * @ORM\Id
     * @ORM\Column(type="integer", unique=true, nullable=false)
     */
    private $id;
}
Run Code Online (Sandbox Code Playgroud)

如您所见,我将Gedmo Timestampable与捆绑包提供的Trait一起使用。一切正常。

当我获取数据并且列updated_at正以时出现问题。在这种情况下,对象将转换为无效日期,如下所示:NULL 0000-00-00 00:00:00DateTime

?array (
  'RowId' => 26944,
  'synchflag' => 1,
  'updatedAt' => 
  DateTime::__set_state(array(
     'date' => '-0001-11-30 00:00:00.000000',
     'timezone_type' => 3,
     'timezone' => 'UTC',
  )),
)
Run Code Online (Sandbox Code Playgroud)

我确实检查过文档,但没有任何帮助(或者,如果您让我知道,至少我没有找到它)

解决这个问题的正确方法是什么?

编辑:

也许正确的问题应该是:如果updated_at要来的话,0000-00-00 00:00:00我该如何将其变成NOW()?您可能会注意到,getUpdatedAt()返回的值DateTime基于所获取的数据。有什么要SELECT发表的事件吗?

小智 6

由于问题在于数据库已经具有这些无效值,因此您可以创建自己的学说日期时间类型,以在从数据库中读取无效值时将其转换为null:

<?php
namespace AppBundle\Doctrine\DBAL;

use DateTimeZone;
use Doctrine\DBAL\Platforms\AbstractPlatform;
use Doctrine\DBAL\Types\ConversionException;
use Doctrine\DBAL\Types\DateTimeType;

class MyDateTimeType extends DateTimeType
{


   public function convertToPHPValue($value, AbstractPlatform $platform)
   {
       if (null === $value || $value instanceof \DateTime) {
           return $value;
       }

       if ('0000-00-00 00:00:00' === $value) {
          return null;
       }

       return parent::convertToPHPValue($value, $platform);
   }
}
Run Code Online (Sandbox Code Playgroud)

并在原则配置中注册此自定义类型:

doctrine:
   dbal:
       types:
           datetime: AppBundle\Doctrine\DBAL\MyDateTimeType
Run Code Online (Sandbox Code Playgroud)

注意:您可以使用regexp和/或datetime有效性检查来增强此代码,而不必进行简单的比较