solvit.io

Configure bidirectional many-to-many Doctrine entities

In this example, Article and Tag are entities that define a bidirectional many-to-many relation that is always kept synchronized in both sides. Read the Doctrine documentation to learn how to configure association mappings.

Article.php
<?php

use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;

/**
 * @ORM\Entity()
 */
class Article
{
    /**
     * @ORM\Id()
     * @ORM\GeneratedValue(strategy="AUTO")
     * @ORM\Column(type="integer", name="id")
     */
    protected $id;

    /**
     * @ORM\ManyToMany(targetEntity="Tag", inversedBy="articles")
     */
    protected $tags;

    public function __construct()
    {
        $this->tags = new ArrayCollection();
    }

    public function addTag(Tag $tag)
    {
        if ($this->tags->contains($tag)) {
            return;
        }

        $this->tags->add($tag);
        $tag->addArticle($this);
    }

    public function removeTag(Tag $tag)
    {
        if (!$this->tags->contains($tag)) {
            return;
        }

        $this->tags->removeElement($tag);
        $tag->removeArticle($this);
    }
}
Tag.php
<?php

use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;

/**
 * @ORM\Entity()
 */
class Tag
{
    /**
     * @ORM\Id()
     * @ORM\GeneratedValue(strategy="AUTO")
     * @ORM\Column(type="integer", name="id")
     */
    protected $id;

    /**
     * @ORM\ManyToMany(targetEntity="Article", mappedBy="tags")
     */
    protected $articles;

    public function __construct()
    {
        $this->articles = new ArrayCollection();
    }

    public function addArticle(Article $article)
    {
        if ($this->articles->contains($article)) {
            return;
        }

        $this->articles->add($article);
        $article->addTag($this);
    }

    public function removeArticle(Article $article)
    {
        if (!$this->articles->contains($article)) {
            return;
        }

        $this->articles->removeElement($article);
        $article->removeTag($this);
    }
}
Find more solutions about: , , , ,