Параметр inversedBy атрибута ManyToOne
Параметр inversedBy атрибута ManyToOne
указывает имя свойства в связанной сущности,
которое является обратной стороной связи OneToMany.
Иными словами, он сообщает Doctrine, какое поле
в целевой сущности ссылается на текущую сущность
через коллекцию. Параметр принимает строку с именем
этого свойства и используется вместе с targetEntity.
Синтаксис
#[ManyToOne(targetEntity: Entity::class, inversedBy: 'property')]
Пример
Давайте свяжем сущность Article с сущностью Category
так, чтобы у статьи была одна категория, а у категории -
много статей. В сущности Article укажем inversedBy
на свойство articles:
<?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;
#[ORM\ManyToOne(targetEntity: Category::class, inversedBy: 'articles')]
private ?Category $category = 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;
}
public function getCategory(): ?Category
{
return $this->category;
}
public function setCategory(?Category $category): static
{
$this->category = $category;
return $this;
}
}
?>
Пример
Теперь опишем обратную сторону связи в сущности Category
через атрибут OneToMany с параметром mappedBy:
<?php
namespace App\Entity;
use App\Repository\CategoryRepository;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
#[ORM\Entity(repositoryClass: CategoryRepository::class)]
class Category
{
#[ORM\Id]
#[ORM\GeneratedValue]
#[ORM\Column]
private ?int $id = null;
#[ORM\Column(length: 255)]
private ?string $name = null;
#[ORM\OneToMany(targetEntity: Article::class, mappedBy: 'category')]
private Collection $articles;
public function __construct()
{
$this->articles = new ArrayCollection();
}
public function getId(): ?int
{
return $this->id;
}
public function getName(): ?string
{
return $this->name;
}
public function setName(string $name): static
{
$this->name = $name;
return $this;
}
public function getArticles(): Collection
{
return $this->articles;
}
public function addArticle(Article $article): static
{
if (!$this->articles->contains($article)) {
$this->articles->add($article);
$article->setCategory($this);
}
return $this;
}
public function removeArticle(Article $article): static
{
if ($this->articles->removeElement($article)) {
if ($article->getCategory() === $this) {
$article->setCategory(null);
}
}
return $this;
}
}
?>
Пример
Давайте создадим категорию, добавим в неё статью и выведем список заголовков статей категории:
<?php
namespace App\Controller;
use App\Entity\Article;
use App\Entity\Category;
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_index')]
public function index(EntityManagerInterface $em): Response
{
$category = new Category();
$category->setName('abcde');
$article = new Article();
$article->setTitle('hello');
$article->setCategory($category);
$em->persist($category);
$em->persist($article);
$em->flush();
$res = [];
foreach ($category->getArticles() as $item) {
$res[] = $item->getTitle();
}
return new Response(implode(', ', $res));
}
}
?>
Результат выполнения кода:
hello
Смотрите также
-
атрибут
ManyToOne,
который задаёт связь многие-к-одному -
атрибут
OneToMany,
который задаёт связь один-ко-многим -
параметр
targetEntity,
который задаёт целевую сущность связи -
параметр
mappedBy,
который указывает владеющую сторону связи