gpt4 book ai didi

datetime - Symfony/Doctrine : DateTime as primary key

转载 作者:行者123 更新时间:2023-12-04 23:55:24 27 4
gpt4 key购买 nike

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

我怎么解决这个问题?谢谢你。

最佳答案

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

关于datetime - Symfony/Doctrine : DateTime as primary key,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17125863/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com