Symfony/Doctrine:日期时间作为主键 [英] Symfony/Doctrine: DateTime as primary key

查看:15
本文介绍了Symfony/Doctrine:日期时间作为主键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用日期作为主键来创建实体.问题是 Symfony 无法将我使用的 DateTime 转换为字符串以将其引入 IdentityMap 中.在实体持久化过程中出现以下错误:

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..

我在实体中使用此代码:

/**
 * @ORMId
 * @ORMColumn(type="datetime")
 */
protected $date;

实体仓库中出现错误:

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

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

How can I solve this problem? Thank you.

推荐答案

一个可靠的解决方案是实现你自己的 DBAL 类型,使用 DateTime 的后代并实现 __toString():

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 DoctrineDBALTypesDateType{
    public function convertToPHPValue($value, DoctrineDBALPlatformsAbstractPlatform $platform) {
        $value = parent::convertToPHPValue($value, $platform);
        if ($value !== NULL) {
            $value = DateKey::fromDateTime($value);
        }
        return $value;
    }
    public function getName()
    {
        return 'DateKey';
    }
}

DoctrineDBALTypesType::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(DoctrineDBALTypesType::getType('datekey'));

这篇关于Symfony/Doctrine:日期时间作为主键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆