Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony/Doctrine: DateTime as primary key

I am trying to make an Entity using a date as a primary key. The problem is that Symfony can't convert the DateTime I'm using into a string to introduce it in the IdentityMap. I get the following error during the persist of the entity:

Catchable Fatal Error: Object of class DateTime could not be converted to string in..

I'm using this code in the entity:

/**
 * @ORM\Id
 * @ORM\Column(type="datetime")
 */
protected $date;

The error appears in the entity repository:

$em = $this->getEntityManager();
$currentData = new CurrentData();
...
$currentData->setDate(new \DateTime($dateStr));
...
$em->persist($currentData);
$em->flush();

How can I solve this problem? Thank you.

like image 722
Miguel Avatar asked Jun 15 '13 16:06

Miguel


2 Answers

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'));
like image 59
amik Avatar answered Dec 03 '22 00:12

amik


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.

like image 35
blaimi Avatar answered Dec 03 '22 00:12

blaimi