Атрибут Id
Атрибут Id вешается на свойство
класса-сущности и указывает Doctrine, что
это свойство является первичным ключом
таблицы. Параметров у атрибута нет. Обычно
он используется вместе с атрибутом
GeneratedValue, который включает
автоматическую генерацию значения ключа.
Синтаксис
#[Id]
Пример
Давайте создадим сущность Article
с автоинкрементным первичным ключом id:
<?php
namespace App\Entity;
use App\Repository\ArticleRepository;
use Doctrine\ORM\Mapping as ORM;
#[ORM\Entity(repositoryClass: ArticleRepository::class)]
class Article
{
#[ORM\Id]
#[ORM\GeneratedValue]
#[ORM\Column]
private ?int $id = null;
#[ORM\Column(length: 255)]
private ?string $title = null;
public function getId(): ?int
{
return $this->id;
}
public function getTitle(): ?string
{
return $this->title;
}
public function setTitle(string $title): static
{
$this->title = $title;
return $this;
}
}
?>
Теперь создадим контроллер, который сохранит сущность в базу данных и выведет сгенерированный идентификатор:
<?php
namespace App\Controller;
use App\Entity\Article;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;
class ArticleController extends AbstractController
{
#[Route('/article', name: 'article_create')]
public function create(EntityManagerInterface $em): Response
{
$article = new Article();
$article->setTitle('hello');
$em->persist($article);
$em->flush();
return new Response((string) $article->getId());
}
}
?>
Результат выполнения кода:
"1"
Пример
Давайте сделаем первичный ключ строковым и зададим его значение вручную, без автогенерации:
<?php
namespace App\Entity;
use App\Repository\ArticleRepository;
use Doctrine\ORM\Mapping as ORM;
#[ORM\Entity(repositoryClass: ArticleRepository::class)]
class Article
{
#[ORM\Id]
#[ORM\Column(length: 255)]
private ?string $id = null;
#[ORM\Column(length: 255)]
private ?string $title = null;
public function getId(): ?string
{
return $this->id;
}
public function setId(string $id): static
{
$this->id = $id;
return $this;
}
public function getTitle(): ?string
{
return $this->title;
}
public function setTitle(string $title): static
{
$this->title = $title;
return $this;
}
}
?>
Теперь сохраним сущность с ключом 'abcde':
<?php
namespace App\Controller;
use App\Entity\Article;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;
class ArticleController extends AbstractController
{
#[Route('/article', name: 'article_create')]
public function create(EntityManagerInterface $em): Response
{
$article = new Article();
$article->setId('abcde');
$article->setTitle('hello');
$em->persist($article);
$em->flush();
return new Response($article->getId());
}
}
?>
Результат выполнения кода:
"abcde"
Пример
Давайте добавим в сущность составной
первичный ключ из двух полей. Атрибут
Id в этом случае вешается на каждое
из них:
<?php
namespace App\Entity;
use App\Repository\ArticleRepository;
use Doctrine\ORM\Mapping as ORM;
#[ORM\Entity(repositoryClass: ArticleRepository::class)]
class Article
{
#[ORM\Id]
#[ORM\Column(length: 255)]
private ?string $id = null;
#[ORM\Id]
#[ORM\Column]
private ?int $version = null;
#[ORM\Column(length: 255)]
private ?string $title = null;
public function getId(): ?string
{
return $this->id;
}
public function setId(string $id): static
{
$this->id = $id;
return $this;
}
public function getVersion(): ?int
{
return $this->version;
}
public function setVersion(int $version): static
{
$this->version = $version;
return $this;
}
public function getTitle(): ?string
{
return $this->title;
}
public function setTitle(string $title): static
{
$this->title = $title;
return $this;
}
}
?>
Теперь сохраним сущность с двумя полями ключа:
<?php
namespace App\Controller;
use App\Entity\Article;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;
class ArticleController extends AbstractController
{
#[Route('/article', name: 'article_create')]
public function create(EntityManagerInterface $em): Response
{
$article = new Article();
$article->setId('abcde');
$article->setVersion(1);
$article->setTitle('hello');
$em->persist($article);
$em->flush();
return new Response($article->getId() . '-' . $article->getVersion());
}
}
?>
Результат выполнения кода:
"abcde-1"
Смотрите также
-
атрибут
Entity,
который помечает класс как сущность Doctrine -
атрибут
GeneratedValue,
который включает автогенерацию значения ключа -
атрибут
Table,
который задаёт имя таблицы для сущности -
атрибут
CustomIdGenerator,
который задаёт свой генератор первичного ключа