簡體   English   中英

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

[英]Doctrine 2: Can't update DateTime column on SQL Server 2008apm

我在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);

有人知道這里的解決方法嗎?

我在Doctrine 2.5和SQL Server 2012中遇到了這個問題。問題是數據庫字段是DATETIME類型,但是doctirne只支持SQLServer2008Platform及更高版本的DATETIME2

您不應該編輯供應商目錄中的文件。 正確答案是創建自定義類型: Doctrine自定義映射類型 在我的例子中,我擴展了當前的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

它是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;
}

你傳遞給datetime字段有什么價值? 您應該傳遞Datetime實例

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

我仍然遇到與Microsoft SQL Server Express 17和Doctrine ORM v2.6.3 / DBAL v2.9.2相同的問題。 (對於Doctrine Platform,我使用SQLServer2012Platform )。

您需要做的就是將SQL字段從DATETIME更改為DATETIME2類型(盡可能)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM