Search code examples
symfonyinsertdoctrinemany-to-manyjunction-table

how to insert into junction table when many to many with doctrine?


I am trying to insert into a junction table called post_post_category which is based on Post and PostCategory tables [many to many], i manage to execute the insert but the problem is that when i add a new post it creates a new category.

Post Entity:

class Post
{

...

 /**
 *  @ORM\ManyToMany(targetEntity="PostCategory", cascade={"persist"})
 *  @ORM\JoinTable(name="post_post_category",
 *      joinColumns={@ORM\JoinColumn(name="post_id", referencedColumnName="id")},
 *      inverseJoinColumns={@ORM\JoinColumn(name="post_category_id", referencedColumnName="id")}
 *   )
 */
private $categories;

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

...

public function getCategories(): ?PostCategory
{
    return $this->categories;
}

public function addCategory(PostCategory $category): self
{
    $this->categories->add($category);

    return $this;
}
}

Category Entity:

class PostCategory
{
    /**
     * @ORM\Id()
     * @ORM\GeneratedValue()
     * @ORM\Column(type="integer")
     */
    private $id;

    /**
     * @ORM\Column(type="string", length=60)
     */
    private $category_description;

    public function getId()
    {
        return $this->id;
    }

    public function getCategoryDescription(): ?string
    {
        return $this->category_description;
    }

    public function setCategoryDescription(string $category_description): self
    {
        $this->category_description = $category_description;

        return $this;
    }    
}

Controller:

...

$category->setCategoryDescription('New category');
$post->addCategory($category);

$database_manager->persist($post);
$database_manager->flush();

How do i insert an existing category in junction table?


Solution

  • to add an existing category to a Post you will have to retrieve the category from the database

    $category = $em->getRepository('AppBundle:PostCategory')->find($categoryId);
    $post->addCategory($category);