Doctrine ORM:NULL转DateTime错误(PHP7+Symfony2.8环境)
解决Doctrine 2.5返回零DateTime对象而非NULL的问题
我之前也踩过这个坑!在Doctrine ORM 2.5里,哪怕你给datetime字段设置了nullable=true,默认逻辑还是会把数据库里的NULL值(或是MySQL里常用的0000-00-00无效日期)转换成一个特殊的"零"DateTime对象,也就是你看到的-0001-11-30 00:00:00。这是早期Doctrine类型处理的默认设计,不过有两种简单的解决办法:
方法一:在实体Getter中手动处理(快速生效)
直接修改你的getDataOrdine()方法,检查返回的DateTime是否是这个特殊的零日期,是的话就返回NULL:
/** * @return \DateTime|null */ public function getDataOrdine() { // 识别Doctrine生成的零日期对象 if ($this->dataOrdine instanceof \DateTime && $this->dataOrdine->format('Y-m-d') === '-0001-11-30') { return null; } return $this->dataOrdine; }
这种方法不需要修改Doctrine配置,适合单个字段的快速修复。
方法二:自定义Doctrine类型(全局统一处理)
如果你的项目里有很多类似的nullable DateTime字段,推荐自定义一个Doctrine类型,全局统一把NULL/零日期转换成PHP的NULL:
1. 创建自定义类型类
<?php namespace YourBundle\Doctrine\Type; // 替换成你的Bundle命名空间 use Doctrine\DBAL\Types\DateTimeType; use Doctrine\DBAL\Platforms\AbstractPlatform; class NullableDateTimeType extends DateTimeType { public function convertToPHPValue($value, AbstractPlatform $platform) { // 数据库值为NULL时直接返回NULL if ($value === null) { return null; } $dateTime = parent::convertToPHPValue($value, $platform); // 把零日期转换成NULL if ($dateTime->format('Y-m-d') === '-0001-11-30') { return null; } return $dateTime; } }
2. 注册自定义类型
在Symfony的config.yml中添加Doctrine类型配置:
doctrine: dbal: types: nullable_datetime: YourBundle\Doctrine\Type\NullableDateTimeType
3. 修改实体字段映射
把原来的datetime类型换成自定义的nullable_datetime:
/** @ORM\Column(name="data_ordine", type="nullable_datetime", nullable=true) */ private $dataOrdine;
这样所有使用这个类型的字段都会自动把NULL/零日期转换成PHP的NULL,一劳永逸。
顺便提一句:你看到的-0001-11-30其实是DateTime类处理MySQL的0000-00-00无效日期时的转换结果——因为公历没有公元0年,日期计算时会产生这个偏移值。
内容的提问来源于stack exchange,提问作者marchiosim
相关产品推荐
相关产品推荐

