Symfony / Doctrine: DateTime as primary key

I am trying to create an entity using date as primary key. The problem is that Symfony cannot convert the DateTime that I use to a string to enter it in IdentityMap. I get the following error while saving an object:

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

I use this code in an object :

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

The error appears in the repository. :

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

How can I solve this problem? Thanks.

+4
source share
3 answers

The solution to this solution is to implement a native DBAL type using a DateTime descendant with implemented __toString ():

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

You should probably just use the usual sequence.

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

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

You are probably in trouble if you try to use the datetime object for a key.

+1
source

I had the same problem. I worked on this using this:

 /** * @var string * * @ORM\Id * @ORM\Column(type="string") */ private $date; /** * @return \DateTime */ public function getDate() { return \DateTime::createFromFormat('Ymd|', $this->date); } /** * @param \DateTime $date */ public function __construct(\DateTime $date) { $this->date = $date->format('Ym-d'); } 

if you want to use datetime, you must use a different format like \ DateTime :: ISO8601. Be careful when saving things with time zones.

+1
source

Source: https://habr.com/ru/post/1486408/


All Articles