Created
January 12, 2023 13:15
-
-
Save ninsuo/821f98911617e569d9eb3f5e490bf5c1 to your computer and use it in GitHub Desktop.
Let the db manage created at / updated at fields with Doctrine
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace Dot\SkeletonBundle\Doctrine\DBAL\Types; | |
use Doctrine\DBAL\Platforms\AbstractPlatform; | |
class CreatedAtType extends DateTimeImmutableUTCType | |
{ | |
public const NAME = 'created_at'; | |
public function getSQLDeclaration(array $fieldDeclaration, AbstractPlatform $platform): string | |
{ | |
return 'DATETIME DEFAULT CURRENT_TIMESTAMP'; | |
} | |
public function getName(): string | |
{ | |
return self::NAME; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class User | |
{ | |
#[ORM\Column(type: CreatedAtType::NAME, insertable: false, updatable: false)] | |
private ?\DateTimeImmutable $createdAt = null; | |
#[ORM\Column(type: UpdatedAtType::NAME, insertable: false, updatable: false)] | |
private ?\DateTimeImmutable $updatedAt = null; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace Dot\SkeletonBundle\Doctrine\DBAL\Types; | |
use Doctrine\DBAL\Platforms\AbstractPlatform; | |
class UpdatedAtType extends DateTimeImmutableUTCType | |
{ | |
public const NAME = 'updated_at'; | |
public function getSQLDeclaration(array $fieldDeclaration, AbstractPlatform $platform): string | |
{ | |
return 'DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'; | |
} | |
public function getName(): string | |
{ | |
return self::NAME; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment