I use Doctrine2 as ORM in a Symfony2 project. I have article and tag entity classes. There are many-to-many relations between them. An article may have many tags and vice versa. There is a joined table, article_tags which just have 2 columns article_id and tag_id, and generated by doctrine. Everything works fine, except, when new article with some tags is added, both new and pre-existing tags are inserted into tag table in which I want to only store unique tags; the article_tags should just relate them.
My article schema:
manyToMany:
tags:
targetEntity: Tag
cascade: ["persist"]
joinTable:
name: article_tag
joinColumns:
article_id:
referencedColumnName: id
inverseJoinColumns:
tag_id:
referencedColumnName: id
Adding unique attribute to tag and ignoring duplicates is not reasonable since there should be relation. I tried to add logic that checks if the tag exists fetch tag data and add it to article:
$article->addTag($existingTag);
It gives the following error:
Catchable Fatal Error: Argument 1 passed to
Seferov\ArticleBundle\Entity\Article::addTag() must be an instance of
Seferov\ArticleBundle\Entity\Tag, null given, called in
/var/www/seferov.local/src/Seferov/ArticleBundle/Repository/TagRepository.php
on line 34 and defined in
/var/www/seferov.local/src/Seferov/ArticleBundle/Entity/Article.php
line 393
You basically need to check if the tag exists. If it does then use it. If not then create one.
Be sure to make your tag column unique and to catch exceptions. Possibility that another request might insert the same tag in between the find and the persist.