I have a scenario where I’m updating a blog post which has multiple tags assigned to it via a many to many relationship (in a link table called blog_link_tags) as below:
...
$em = $this->getDoctrine()->getManager();
$blogPost = $em->getRepository('MyBlogBundle:Blog')->find($postId);
$blogPost
->setTitle( $request->request->get('post_title', '') )
->setBody( $request->request->get('post_body', '') )
->setLive(true);
$postTags = json_decode( $request->request->get('post_tags', '') );
$tagRepository = $em->getRepository('MyBlogBundle:BlogTag');
foreach($postTags as $postTag) {
$tag = $tagRepository->find( $postTag->id );
if (!$tag) {
throw $this->createNotFoundException('Tag not found: ' . $tag->title);
}
$blogPost->addTag($tag);
}
$em->flush();
....
As you can probably tell though, if I edit a blog post and add a new tag then it will create duplicates records.
What is the best way to either truncate the blog_link_tag table of records of the current blog post id, OR only insert those tag ids that are unique? Would it be to do it on the following line within the foreach loop:
$tag = $tagRepository->find( $postTag->id );
But instead check to see if the tag existed AND if it was not yet present in the link table? Or does Doctrine 2 offer a better way to achieve such an action?
As far as I’m concerned I would first create a FormType for the Post entity so that I don’t have to write any messy code into the controller and everything is automated, clean and secure.
Next, I would manage the tags within the Post entity as in: