我有以下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;
}
正如您所看到的,我正在使用Gedmo Timestampable与捆绑包提供的Trait。它工作正常。
当我获取数据并且updated_at
列来自 NULL
0000-00-00 00:00:00
时,会出现问题。对于这种情况,DateTime
对象被转换为无效日期,如下所示:
array (
'RowId' => 26944,
'synchflag' => 1,
'updatedAt' =>
DateTime::__set_state(array(
'date' => '-0001-11-30 00:00:00.000000',
'timezone_type' => 3,
'timezone' => 'UTC',
)),
)
我确实检查了docs但是没有任何帮助(或者至少我没有找到它,如果你让我知道的话)
解决这个问题的正确方法是什么?
修改
也许正确的问题应该是:如果updated_at
即将0000-00-00 00:00:00
,我该如何将其变为NOW()
?您可能会注意到getUpdatedAt()
根据提取的数据返回DateTime
。 SELECT
声明是否有任何事件?
答案 0 :(得分:3)
由于问题是数据库已经存在这些无效值,您可以创建自己的doctrine datetime类型,以便在从数据库中读取该无效值时将转换为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);
}
}
在学说配置中注册此自定义类型:
doctrine:
dbal:
types:
datetime: AppBundle\Doctrine\DBAL\MyDateTimeType
注意:您可以使用regexp和/或日期时间有效性检查来增强此代码,而不是简单的比较