1
我正在学习SF2 - 对完成的工作印象深刻,面临我无法解决的第一个真正问题。Symfony 2:ManyToMany关系和独特对象
我有两个实体:Post和Tag。下面缩短代码:
class Tag
{
/**
* @ORM\ManyToMany(targetEntity="Post", mappedBy="tags", cascade={"persist"})
*/
private $posts;
public function __construct()
{
$this->posts = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
* @param \My\AppBundle\Entity\Snippet $posts
* @return Tag
*/
public function addSnippet(\My\AppBundle\Entity\Post $posts)
{
$this->posts[] = $posts;
return $this;
}
/**
* @param \My\AppBundle\Entity\Snippet $snippets
*/
public function removeSnippet(\My\AppBundle\Entity\Post $posts)
{
$this->posts->removeElement($posts);
}
/**
* @return \Doctrine\Common\Collections\Collection
*/
public function getSnippets()
{
return $this->posts;
}
}
class Post
{
/**
* @ORM\ManyToMany(targetEntity="Tag", inversedBy="posts", cascade={"persist"})
* @ORM\JoinTable(name="posts_tags",
* joinColumns={@ORM\JoinColumn(name="post_id", referencedColumnName="id", unique=true, onDelete="cascade")},
* inverseJoinColumns={@ORM\JoinColumn(name="tag_id", referencedColumnName="id", unique=true, onDelete="cascade")}
*)
*/
private $tags;
public function __construct()
{
$this->tags = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
* @param \My\AppBundle\Entity\Tag $tags
* @return Snippet
*/
public function addTag(\My\AppBundle\Entity\Tag $tags)
{
$this->tags[] = $tags;
return $this;
}
/**
* @param \My\AppBundle\Entity\Tag $tags
*/
public function removeTag(\My\AppBundle\Entity\Tag $tags)
{
$this->tags->removeElement($tags);
}
/**
* @return \Doctrine\Common\Collections\Collection
*/
public function getTags()
{
return $this->tags;
}
}
正如你可以看到我有L:两个实体m之间的关系。
我也有一个形式与嵌入式标签集合添加帖子:
$builder
->add('title')
->add('tags', 'collection', array(
'type' => new \My\AppBundle\Form\TagType(),
'allow_add' => true,
'by_reference' => false,
'prototype' => true
))
;
TagType窗体类:
$builder->add('name');
一切正常。除了一件事:如果有一个以下名称的标签对象,我得到SQLSTATE[23000]: Integrity constraint violation
MySQL错误,这是显而易见的。如果我应用独特的验证约束,我可以添加标签发布(如果它已经存在于数据库中)。
很明显,我需要检查数据库中是否存在以下标记,并且只在不存在的情况下才添加它,但是......如何执行Symfony方式?
任何建议表示赞赏!
要回答潜在的问题:不,不想使用任何现有的捆绑软件,需要在SO社区的帮助下自己学习。 – user1854344