2013-01-05 70 views
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方式?

任何建議表示讚賞!

+0

要回答潛在的問題:不,不想使用任何現有的捆綁軟件,需要在SO社區的幫助下自己學習。 – user1854344

回答

1

您可以使用UniqueEntity來解決這個問題。我無法在您的標記類或您的'名稱'聲明上看到您的註釋,但是如果您添加類似於下面的內容,它應該爲您提供基於名稱的唯一驗證約束,並附帶可選消息以回饋。

/** 
* @ORM\Entity 
* @UniqueEntity(fields="name", message="This tag name already exists") 
*/ 
class Tag... 

/** 
* @var string $name 
* 
* @ORM\Column(name="name", type="string", length=255, unique=true) 
*/ 
protected $name;