具有SQL Server DateTime类型的原则



我在Laravel上开发一个依赖于Doctrine的Web应用程序。数据库存储在SQL Express 2017上。

当我执行SELECT时,文档中提到的DateTime类型出现了问题。

无法将数据库值"2018-11-19 16:19:44.923"转换为条令类型datetimetz。预期格式:Y-m-d H:i:s.u P

为了解决这个问题,经过一些研究,我创建了自己的DateTime类型。

<?php
namespace AppDoctrineTypes;
use DoctrineDBALTypesDateTimeType;
use DoctrineDBALPlatformsAbstractPlatform;
class MsDateTime extends DateTimeType
{
private $dateTimeFormatString = 'Y-m-d H:i:s.u';
public function convertToDatabaseValue($value, AbstractPlatform $platform)
{
return ($value !== null) ? $value->format($this->dateTimeFormatString) : null;
}
}

然后我覆盖默认类型:

Type::overrideType(Type::DATETIMETZ, 'AppDoctrineTypesMsDateTime');

因此,现在我可以显示数据,但不能插入新行:使用params["Test"、"Test",1、"2018-11-20 16:12:11.349245"、"2018-11-20 16:12:11:349250"]执行"INSERT INTO table(row1,row2,active,date_created,timestamp(VALUES(?,?,??,?("时发生异常

我想知道为什么我不能存储新行。如果您对使用SQLServer的Doctrine有任何修复,我将不胜感激!

我们还使用Python和SQL Alchemy来查询同一个数据库,我们没有这种问题。

使用Microsoft Sql Server Express 2017时,应首先验证您是否在Doctrine配置/自动加载器中使用了SQLServer2012Platform

我以以下方式指定它(在Codeigniter下(:

$myPlatform = new DoctrineDBALPlatformsSQLServer2012Platform();
$connectionOptions = array(
'driver' => 'pdo_sqlsrv',
'user' => $db['default']['username'],
'password' => $db['default']['password'],
'host' => $db['default']['hostname'],
'dbname' => $db['default']['database'],
'platform' => $myPlatform
);

我将所有SQL字段从DATETIME切换到了DATETIME2,插入/更新都运行良好。

我的Doctrine实体是用"datetime"类型定义的,我可以用原生DateTime()对象为它们提供信息。

/**
* @var DateTime
*
* @ORMColumn(type="datetime", nullable = true)
*/
protected $created;
/**
* @var DateTime
*
* @ORMColumn(type="datetime", nullable = true)
*/
protected $updated;
/**
* @ORMPrePersist
* @ORMPreUpdate
*/
public function updatedTimestamps(): void
{
if ($this->created === null) {
$this->created = new DateTime();
}
$this->updated = new DateTime();
}

希望这能有所帮助!

根据已知的问题,我将放弃datetimetz类型。看见条令-已知供应商问题-Microsoft SQL Server

最新更新