Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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');
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.