我正在尝试使用日期作为主键创建一个实体。问题是 Symfony 无法将我正在使用的 DateTime 转换为字符串以将其引入到 IdentityMap 中。在实体持久化期间出现以下错误:
Catchable Fatal Error: Object of class DateTime could not be converted to string in..
我在中使用这段代码entity:
/**
* @ORM\Id
* @ORM\Column(type="datetime")
*/
protected $date;
错误出现在实体存储库:
$em = $this->getEntityManager();
$currentData = new CurrentData();
...
$currentData->setDate(new \DateTime($dateStr));
...
$em->persist($currentData);
$em->flush();
我怎么解决这个问题?谢谢。
对此的一个稳健的解决方案是实现您自己的 DBAL 类型,使用实现了 __toString() 的 DateTime 后代:
<?php
class DateKey extends \DateTime{
function __toString() {
return $this->format('c');
}
static function fromDateTime(\DateTime $dateTime) {
return new static($dateTime->format('c'));
}
}
class DateKeyType extends \Doctrine\DBAL\Types\DateType{
public function convertToPHPValue($value, \Doctrine\DBAL\Platforms\AbstractPlatform $platform) {
$value = parent::convertToPHPValue($value, $platform);
if ($value !== NULL) {
$value = DateKey::fromDateTime($value);
}
return $value;
}
public function getName()
{
return 'DateKey';
}
}
\Doctrine\DBAL\Types\Type::addType('datekey', 'DateKeyType');
//edit: do not forget this after creating entity manager.
//otherwise, you will get into problems with doctrine database diff / migrations.
$platform = $entityManager->getConnection()->getDatabasePlatform();
$platform->registerDoctrineTypeMapping('datekey', 'datekey');
$platform->markDoctrineTypeCommented(\Doctrine\DBAL\Types\Type::getType('datekey'));
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)