Skip to content

Instantly share code, notes, and snippets.

@vaibhavpandeyvpz
Last active March 6, 2023 20:10
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save vaibhavpandeyvpz/7cc475707b0f5772eb24393175620c69 to your computer and use it in GitHub Desktop.
Save vaibhavpandeyvpz/7cc475707b0f5772eb24393175620c69 to your computer and use it in GitHub Desktop.
Populate `created_at` and `updated_at` columns with Symfony & Doctrine.
<?php
namespace App\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Entity(repositoryClass="App\Repository\ExampleRepository")
* @ORM\HasLifecycleCallbacks()
* @ORM\Table("examples")
*/
class Example
{
use Timestamps;
// ...more fields
}
<?php
namespace App\Entity;
use DateTime;
use DateTimeInterface;
use Doctrine\ORM\Mapping as ORM;
trait Timestamps
{
/**
* @ORM\Column(name="created_at", type="datetime", nullable=true)
*/
private $createdAt;
/**
* @ORM\Column(name="updated_at", type="datetime", nullable=true)
*/
private $updatedAt;
public function getCreatedAt(): ?DateTimeInterface
{
return $this->createdAt;
}
public function setCreatedAt(?DateTimeInterface $timestamp): self
{
$this->createdAt = $timestamp;
return $this;
}
public function getUpdatedAt(): ?DateTimeInterface
{
return $this->updatedAt;
}
public function setUpdatedAt(?DateTimeInterface $timestamp): self
{
$this->updatedAt = $timestamp;
return $this;
}
/**
* @ORM\PrePersist
*/
public function setCreatedAtAutomatically()
{
if ($this->getCreatedAt() === null) {
$this->setCreatedAt(new \DateTime());
}
}
/**
* @ORM\PreUpdate
*/
public function setUpdatedAtAutomatically()
{
$this->setUpdatedAt(new \DateTime());
}
}
<?php
declare(strict_types=1);
namespace DoctrineMigrations;
use Doctrine\DBAL\Schema\Schema;
use Doctrine\DBAL\Types\Type;
use Doctrine\Migrations\AbstractMigration;
final class Version00000000000000 extends AbstractMigration
{
public function up(Schema $schema) : void
{
$table = $schema->createTable('examples');
// ...more fields
$table->addColumn('created_at', Type::DATETIME, ['notnull' => false]);
$table->addColumn('updated_at', Type::DATETIME, ['notnull' => false]);
}
public function down(Schema $schema) : void
{
$schema->dropTable('examples');
}
}
@vaibhavpandeyvpz
Copy link
Author

Just did, thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment