我试图使用日期作为主键来创建一个实体。问题是,Symfony不能将我使用的DateTime转换为字符串,以便在IdentityMap中引入它。在实体持久化过程中,我得到以下错误:
Catchable Fatal Error: Object of class DateTime could not be converted to string in..
我在实体中使用这段代码
/**
* @ORM\Id
* @ORM\Column(type="datetime")
*/
protected $date;
错误出现在实体存储库中。
$em = $this->getEntityManager();
$currentData = new CurrentData();
...
$currentData->setDate(new \DateTime($dateStr));
...
$em->persist($currentData);
$em->flush();
我该如何解决这个问题?谢谢。
发布于 2014-11-25 23:24:49
这方面的一个roubust解决方案是使用实现了DateTime ()的__toString()子代来实现自己的DBAL类型:
<?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'));
发布于 2014-08-13 14:28:54
我在这里也有同样的问题。我用这个来解决这个问题:
/**
* @var string
*
* @ORM\Id
* @ORM\Column(type="string")
*/
private $date;
/**
* @return \DateTime
*/
public function getDate()
{
return \DateTime::createFromFormat('Y-m-d|', $this->date);
}
/**
* @param \DateTime $date
*/
public function __construct(\DateTime $date)
{
$this->date = $date->format('Y-m-d');
}
如果要使用datetime,则应该使用不同的格式,如\DateTime::if 8601。在使用时区保存东西时要小心。
发布于 2013-06-15 17:17:23
你也许应该用一个正常的顺序。
但是,如果必须将日历信息用于键,则可能需要将其存储为“string”类型,然后使用php的DateTime格式:
$currentData->setDate(new \DateTime($dateStr)->format('yyyy/mm/dd');
如果您尝试使用datetime对象作为键,您可能会陷入困境。
https://stackoverflow.com/questions/17125863
复制相似问题