Атрибут Index
Атрибут Index вешается на класс сущности
и создаёт индекс для одной или нескольких
колонок таблицы. Индекс ускоряет поиск и выборку
данных по указанным полям. Первым параметром
передаётся массив имён колонок. Вторым параметром
можно передать имя индекса.
Синтаксис
#[Index(columns: ['column1', 'column2'], name: 'index_name')]
Пример
Давайте создадим сущность Article с индексом
по колонке title:
<?php
namespace AppEntity;
use DoctrineORMMapping as ORM;
#[ORMEntity]
#[ORMTable(indexes: [
new ORMIndex(columns: ['title'], name: 'idx_article_title')
])]
class Article
{
#[ORMId]
#[ORMGeneratedValue]
#[ORMColumn(type: 'integer')]
private ?int $id = null;
#[ORMColumn(type: 'string', length: 255)]
private string $title;
public function getId(): ?int
{
return $this->id;
}
public function getTitle(): string
{
return $this->title;
}
public function setTitle(string $title): self
{
$this->title = $title;
return $this;
}
}
?>
Пример
Давайте создадим составной индекс по колонкам
title и createdAt:
<?php
namespace AppEntity;
use DoctrineORMMapping as ORM;
#[ORMEntity]
#[ORMTable(indexes: [
new ORMIndex(columns: ['title', 'createdAt'], name: 'idx_article_title_created')
])]
class Article
{
#[ORMId]
#[ORMGeneratedValue]
#[ORMColumn(type: 'integer')]
private ?int $id = null;
#[ORMColumn(type: 'string', length: 255)]
private string $title;
#[ORMColumn(type: 'datetime')]
private DateTimeInterface $createdAt;
public function getId(): ?int
{
return $this->id;
}
public function getTitle(): string
{
return $this->title;
}
public function setTitle(string $title): self
{
$this->title = $title;
return $this;
}
public function getCreatedAt(): DateTimeInterface
{
return $this->createdAt;
}
public function setCreatedAt(DateTimeInterface $createdAt): self
{
$this->createdAt = $createdAt;
return $this;
}
}
?>
Пример
Давайте применим индекс к таблице через миграцию:
php bin/console make:migration
php bin/console doctrine:migrations:migrate
Результат выполнения кода:
"Index idx_article_title_created created successfully"
Смотрите также
-
атрибут
Entity,
который помечает класс как сущность Doctrine -
атрибут
Table,
который задаёт настройки таблицы сущности -
атрибут
UniqueConstraint,
который создаёт уникальный индекс -
атрибут
Id,
который помечает поле как первичный ключ