Symfony/Doctrine: DateTime as primary key

若如初见. 提交于 2019-12-01 07:09:04

A roubust solution to this is to implement your own DBAL type, using a DateTime descendant with __toString() implemented:

<?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'));

You probably should just use a normal sequence.

However, if you must use calendar information to key, you might want to store it as a 'string' type and then use php's DateTime Format:

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

You are probably headed for misery if you try to use a datetime object for key.

I had the same problem here. I worked around it by using this:

/**
 * @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');
}

if you want to use datetime, you should use a different format like \DateTime::ISO8601. Be careful at saving stuff with timezones.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!