ursusarctosua / doctrine-timestamp
Doctrine 对 MySQL 时间戳类型的实现
v0.1.5
2019-11-24 16:29 UTC
Requires
- php: ^7.1
Requires (Dev)
- doctrine/orm: ^2.6
- friendsofphp/php-cs-fixer: ^2.14
- phpunit/phpunit: ^7.0 || ^8.0
README
这是 Doctrine ORM 的 MySQL 时间戳类型实现。
在 MySQL 中使用 datetime 数据类型时,如果你使用不同时区进行数据库连接可能会出现问题。因此,建议使用时间戳类型,让数据库服务器根据时区重新计算日期值。
由于 Doctrine 没有提供 MySQL 时间戳类型,这个库实现了它。当在实体配置中指定 datetimetz 类型时,它会生成时间戳列。此外,为了避免 DateTime 对象和 MySQL 连接中的时区不匹配,使用 Unix 时间戳将 DateTime 数据从 PHP 传输到 MySQL,反之亦然。
安装
使用 Composer
composer require ursusarctosua/doctrine-timestamp
配置
Doctrine
将此类型注册到 Doctrine 类型系统中,并将其挂钩到数据库平台(参见 Dotrine 自定义映射类型)
<?php use Doctrine\DBAL\Types\Type; Type::addType('datetimetz', 'UrsusArctosUA\DoctrineTimestamp\DBAL\Types\DateTimeTzType'); $conn->getDatabasePlatform() ->registerDoctrineTypeMapping('mysql_datetimetz', 'datetimetz');
Symfony
在配置中注册类型
# config/packages/doctrine.yaml doctrine: dbal: types: datetimetz: UrsusArctosUA\DoctrineTimestamp\DBAL\Types\DateTimeTzType
用法
在映射配置中将此类型指定为字段类型
<?php use Doctrine\ORM\Mapping as ORM; /** * @ORM\Entity() */ class MyPersistentClass { /** * @var \DateTimeInterface * @ORM\Column(type="datetimetz") */ private $field; }
已知问题
- Doctrine 模式生成器在字段标记为非空时生成请求,此时没有任何操作。然而,对于可空字段,它运行正确。