Skip to content

Instantly share code, notes, and snippets.

@ninsuo
Created January 12, 2023 13:15
Show Gist options
  • Save ninsuo/821f98911617e569d9eb3f5e490bf5c1 to your computer and use it in GitHub Desktop.
Save ninsuo/821f98911617e569d9eb3f5e490bf5c1 to your computer and use it in GitHub Desktop.
Let the db manage created at / updated at fields with Doctrine
<?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;
}
}
<?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;
}
<?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