Doctrine 2:无法更新SQL Server 2008apm上的DateTime列

问题描述 投票:6回答:4

我在Apache服务器上使用Doctrine 2.2和php 5.3。

到目前为止,我偶然发现了以下问题:当我尝试更新datetime列时,我得到:SQLSTATE [22007]:[Microsoft] [SQL Server Native Client 10.0] [SQL Server]转换日期和/或时间时转换失败来自字符串。

我甚至走了这么远,进入专栏,然后使用它只加了1天来设置新的日期......相同的结果。

当我改为将数据库中的列和实体从datetime更改为日期时,它按预期运行。

我的主要问题是,有几个字段我需要使用datetime列。

这是我的代码:

(birthdate是我改为日期的专栏......并且是我可能的几个专栏之一):

//This returns the datetime object that represents birthdate from the database 
$help=$object->getBirthDate(); 
$help->setTimestamp(mktime($time[0],$time[1],$time[2],$date[2],$date[1],$date[0])); 
$help->format(\DateTime::ISO8601); 
$object->setBirthDate($help);

有人知道这里的解决方法吗?

php sql-server-2008 datetime doctrine doctrine-orm
4个回答
9
投票

我在Doctrine 2.5和SQL Server 2012中遇到了这个问题。问题是数据库字段是DATETIME类型,但是doctirne只支持SQLServer2008Platform及更高版本的DATETIME2

您不应该编辑供应商目录中的文件。正确答案是创建自定义类型:Doctrine Custom Mapping Types。在我的例子中,我扩展了当前的DateTimeType:

<?php

namespace AppBundle\Doctrine\Type;

use Doctrine\DBAL\Types\DateTimeType;
use Doctrine\DBAL\Platforms\AbstractPlatform;

class DateTime extends DateTimeType
{
    private $dateTimeFormatString = 'Y-m-d H:i:s.000';

    public function convertToDatabaseValue($value, AbstractPlatform $platform)
    {
        return ($value !== null)
            ? $value->format($this->dateTimeFormatString) : null;
    }

}

然后在Symfony config.yml中:

    types:
      datetime: AppBundle\Doctrine\Type\DateTime

6
投票

它是Doctrine 2.2中的官方错误,将在2.3中得到解决。

微秒被转换为具有错误数量的零的字符串。

解决方法:在文件/Doctrine/DBAL/Types/DateTimeType.php中更改函数convertToDatabaseValue:

public function convertToDatabaseValue($value, AbstractPlatform $platform)
{
   if( $value === null)
      return null;

   $value = $value->format($platform->getDateTimeFormatString());

   if( strlen($value) == 26 &&
         $platform->getDateTimeFormatString() == 'Y-m-d H:i:s.u' &&
         ($platform instanceof \Doctrine\DBAL\Platforms\SQLServer2008Platform
          ||
         $platform instanceof \Doctrine\DBAL\Platforms\SQLServer2005Platform
         ) )
      $value = substr($value, 0, \strlen($value)-3);
   return $value;
}

0
投票

你传递给datetime领域有什么价值?你应该传递一个Datetime实例

$entity->setDate(new \Datetime());

0
投票

我仍然遇到与Microsoft SQL Server Express 17和Doctrine ORM v2.6.3 / DBAL v2.9.2相同的问题。 (对于Doctrine平台,我使用SQLServer2012Platform)。

您需要做的就是将您的SQL字段从DATETIME更改为DATETIME2类型(尽可能)

© www.soinside.com 2019 - 2024. All rights reserved.