Symfony / Doctrine:DateTime作为主键

时间:2013-06-15 16:50:53

标签: datetime symfony doctrine primary-key

我正在尝试使用日期作为主键创建实体。问题是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();

我该如何解决这个问题?谢谢。

3 个答案:

答案 0 :(得分:4)

对此的一个解决方案是实现自己的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'));

答案 1 :(得分:1)

您可能应该只使用正常序列。

但是,如果您必须使用日历信息来键入,您可能希望将其存储为“字符串”类型,然后使用php的DateTime格式:

 $currentData->setDate(new \DateTime($dateStr)->format('yyyy/mm/dd');

如果您尝试使用日期时间对象作为密钥,则可能会导致痛苦。

答案 2 :(得分:1)

我在这里遇到了同样的问题。我用它来解决这个问题:

/**
 * @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 :: ISO8601。小心保存带有时区的东西。