Атрибут OneToOne
Атрибут OneToOne вешается на свойство сущности
и создаёт связь с другой сущностью, где одной записи
первой таблицы соответствует ровно одна запись второй.
Первым параметром передаётся целевая сущность
targetEntity. Дополнительно можно указать
mappedBy, inversedBy, cascade,
fetch и orphanRemoval.
Синтаксис
#[OneToOne(targetEntity: Entity::class, mappedBy: 'property')]
Пример
Давайте создадим две сущности: User и Profile,
где у пользователя ровно один профиль. Сущность
Profile будет владельцем связи:
<?php
namespace AppEntity;
use DoctrineORMMapping as ORM;
#[ORMEntity]
class User
{
#[ORMId]
#[ORMGeneratedValue]
#[ORMColumn(type: 'integer')]
private ?int $id = null;
#[ORMColumn(type: 'string', length: 255)]
private string $name;
#[ORMOneToOne(targetEntity: Profile::class, mappedBy: 'user')]
private ?Profile $profile = null;
public function getId(): ?int
{
return $this->id;
}
public function getName(): string
{
return $this->name;
}
public function setName(string $name): self
{
$this->name = $name;
return $this;
}
public function getProfile(): ?Profile
{
return $this->profile;
}
public function setProfile(?Profile $profile): self
{
$this->profile = $profile;
return $this;
}
}
?>
Теперь опишем сущность Profile с обратной стороной связи:
<?php
namespace AppEntity;
use DoctrineORMMapping as ORM;
#[ORMEntity]
class Profile
{
#[ORMId]
#[ORMGeneratedValue]
#[ORMColumn(type: 'integer')]
private ?int $id = null;
#[ORMColumn(type: 'text')]
private string $bio;
#[ORMOneToOne(targetEntity: User::class, inversedBy: 'profile')]
#[ORMJoinColumn(name: 'user_id', referencedColumnName: 'id')]
private ?User $user = null;
public function getId(): ?int
{
return $this->id;
}
public function getBio(): string
{
return $this->bio;
}
public function setBio(string $bio): self
{
$this->bio = $bio;
return $this;
}
public function getUser(): ?User
{
return $this->user;
}
public function setUser(?User $user): self
{
$this->user = $user;
return $this;
}
}
?>
Пример
Давайте сохраним пользователя вместе с профилем и выведем данные:
<?php
namespace AppController;
use AppEntityProfile;
use AppEntityUser;
use DoctrineORMEntityManagerInterface;
use SymfonyBundleFrameworkBundleControllerAbstractController;
use SymfonyComponentHttpFoundationResponse;
use SymfonyComponentRoutingAttributeRoute;
class UserController extends AbstractController
{
#[Route('/user', name: 'user_create')]
public function create(EntityManagerInterface $em): Response
{
$user = new User();
$user->setName('abcde');
$profile = new Profile();
$profile->setBio('article');
$profile->setUser($user);
$em->persist($user);
$em->persist($profile);
$em->flush();
return new Response('user: ' . $user->getName());
}
}
?>
Результат выполнения кода:
user: abcde
Пример
Давайте получим профиль пользователя через репозиторий и выведем его описание:
<?php
namespace AppController;
use AppEntityUser;
use DoctrineORMEntityManagerInterface;
use SymfonyBundleFrameworkBundleControllerAbstractController;
use SymfonyComponentHttpFoundationResponse;
use SymfonyComponentRoutingAttributeRoute;
class UserController extends AbstractController
{
#[Route('/user/{id}', name: 'user_show')]
public function show(int $id, EntityManagerInterface $em): Response
{
$user = $em->getRepository(User::class)->find($id);
$bio = $user->getProfile()->getBio();
return new Response('bio: ' . $bio);
}
}
?>
Результат выполнения кода:
bio: article
Смотрите также
-
атрибут
ManyToOne,
который создаёт связь многие к одному -
атрибут
OneToMany,
который создаёт связь один ко многим -
атрибут
JoinColumn,
который задаёт колонку внешнего ключа -
параметр
mappedBy,
который указывает владеющую сторону связи