gpt4 book ai didi

php - 如何在 Doctrine2 SELECT 查询中处理 DateTime 类型的默认值?

转载 作者:可可西里 更新时间:2023-11-01 00:40:03 24 4
gpt4 key购买 nike

我有以下 Doctrine2 实体:

<?php

use Doctrine\ORM\Mapping as ORM;
use Gedmo\Timestampable\Traits\TimestampableEntity;
/**
* @ORM\Entity
*/
class Account
{
use TimestampableEntity;

/**
* @var integer
*
* @ORM\Id
* @ORM\Column(type="integer", unique=true, nullable=false)
*/
private $id;
}

如你所见,我正在使用 Gedmo TimestampableTrait由 bundle 提供。一切正常。

当我获取数据并且 updated_at 列为 NULL 0000-00-00 00 时,问题发生了: 00:00。对于这种情况,DateTime 对象被转换为一个无效 日期,如下所示:

‌array (
'RowId' => 26944,
'synchflag' => 1,
'updatedAt' =>
DateTime::__set_state(array(
'date' => '-0001-11-30 00:00:00.000000',
'timezone_type' => 3,
'timezone' => 'UTC',
)),
)

我检查了docs但没有任何帮助(或者至少如果你让我知道我没有找到它)

处理这个问题的正确方法是什么?

编辑:

也许这里正确的问题应该是:如果 updated_at0000-00-00 00:00:00 的形式出现,我如何将它变成 NOW ()?正如您可能注意到的那样,getUpdatedAt() 根据获取的数据返回一个 DateTimeSELECT语句有没有事件?

最佳答案

由于问题是数据库已经有这些无效值,您可以创建自己的 Doctrine 日期时间类型,以便在从数据库中读取无效值时将其转换为 null:

<?php
namespace AppBundle\Doctrine\DBAL;

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

class MyDateTimeType extends DateTimeType
{


public function convertToPHPValue($value, AbstractPlatform $platform)
{
if (null === $value || $value instanceof \DateTime) {
return $value;
}

if ('0000-00-00 00:00:00' === $value) {
return null;
}

return parent::convertToPHPValue($value, $platform);
}
}

并在 doctrine 配置中注册这个自定义类型:

doctrine:
dbal:
types:
datetime: AppBundle\Doctrine\DBAL\MyDateTimeType

注意:您可以使用正则表达式和/或日期时间有效性检查而不是简单比较来增强此代码

关于php - 如何在 Doctrine2 SELECT 查询中处理 DateTime 类型的默认值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44398663/

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