Атрибут ManyToOne
Атрибут ManyToOne вешается на свойство
сущности и указывает, что много записей текущей
сущности ссылаются на одну запись другой сущности.
Первым параметром передаётся целевая сущность.
В параметре inversedBy указывается имя
свойства обратной связи в целевой сущности.
Синтаксис
#[ManyToOne(targetEntity: Entity::class, inversedBy: 'property')]
Пример
Давайте создадим сущности Category и
Article и свяжем их отношением
многие к одному:
<?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(mappedBy: 'category', targetEntity: Article::class)]
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;
}
}
?>
<?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')]
#[ORM\JoinColumn(nullable: false)]
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;
}
}
?>
Пример
Давайте сохраним статью с привязкой к категории:
<?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/create', name: 'article_create')]
public function create(EntityManagerInterface $em): Response
{
$category = new Category();
$category->setName('abcde');
$em->persist($category);
$article = new Article();
$article->setTitle('hello');
$article->setCategory($category);
$em->persist($article);
$em->flush();
return new Response('saved');
}
}
?>
Результат выполнения кода:
"saved"
Смотрите также
-
атрибут
OneToMany,
который задаёт обратную связь один ко многим -
атрибут
JoinColumn,
который настраивает колонку внешнего ключа -
параметр
inversedBy,
который задаёт имя обратного свойства -
параметр
fetch,
который задаёт стратегию загрузки связи