Symfony2 : ManyToMany relation and Collection form type

标签 symfony doctrine-orm

在我的 Symfony2 项目中,我遇到了 ManyToMany 关系的 Collection 表单类型的大问题。

环境: - 交响乐 2.0.14 - 学说 2.1

这是一些代码:

帖子实体

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

/**
 * @ORM\Column(type="string", length=255, nullable=false)
 */
private $title;

/**
 * @ORM\ManyToMany(targetEntity="Tag", inversedBy="posts", cascade={"persist"})
 * @ORM\JoinTable(name="posts_tags")
 */
private $tags;

public function setTags(\Doctrine\Common\Collections\ArrayCollection $tags)
{
    foreach($tags as $tag)
    {
        $tag->addSnippet($this);
    }
}

public function addTag(\My\BlogBundle\Entity\Tag $tags)
{
    $this->tags[] = $tags;
}

public function getTags()
{
    return $this->tags;
}

标记实体

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

/**
 * @var string $name
 * 
 * @ORM\Column(type="string", length=100, unique=true, nullable=false)
 */
private $name;

/**
 * @var Snippet
 * 
 * @ORM\ManyToMany(targetEntity="Post", mappedBy="tags") 
 */
private $posts;

public function addSnippet(\My\BlogBundle\Entity\Post $posts)
{
    $this->posts[] = $posts;
}

PostType 表单类

->add('tags', 'collection', array(
            'type' => new TagType(),
            'allow_add' => true,
            'prototype' => true,
            'by_reference' => false,
        ))

一切正常,但在插入数据库中已存在的标记时抛出错误 SQLSTATE[23000]:违反完整性约束:1062 键“UNIQ_6FBC94265E237E06”的重复条目“tag1”

您是否有任何解决此问题的方法,或者我是否遗漏了什么?我的 Controller 是由 app/console 生成的标准 CRUD Controller 。在此处输入代码

最佳答案

好吧,我不太关心学说,但您似乎是在同一个集合中插入一个具有相同 ID/名称的标签。我想你可以在插入之前检查标签是否存在

public function existTags(\Doctrine\Common\Collections\ArrayCollection $tags)
{
    foreach($this->tags as $tag)
    {
        if ( $tag->getID() === $tags->getId() )
            return true;
    }
    return false;
}

然后

public function addTag(\My\BlogBundle\Entity\Tag $tags)
{
    if ( !$this->existTag($tags) );
        $this->tags[] = $tags;
}

这些是我的模型:

namespace models;


/**
 * @Entity
 * @Table(name="tag")
 */
class Tag
{

    /**
     * @Id @Column(type="integer", nullable=false, name="id")
     * @GeneratedValue(strategy="AUTO")
     */
    protected $id;


    /**
     * @Column(type="string", nullable=false)
     */
    protected $name;

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

    public function setId($id){ $this->id = $id; }
    public function setName($name){ $this->name = $name; }


}

博客条目:

namespace models;

use \Doctrine\Common\Collections\ArrayCollection;

/**
 * @Entity
 * @Table(name="entry")
 */
class Entry
{

    /**
     * @Id @Column(type="integer", nullable=false, name="id")
     * @GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * @Column(type="string", nullable=false, name="body")
     */
    protected $body;



    /**
     * @ManyToMany(targetEntity="Tag")
     * @JoinTable(name="entry_tagged",
     *      joinColumns={@JoinColumn(name="entry_id", referencedColumnName="id")},
     *      inverseJoinColumns={@JoinColumn(name="tag_id", referencedColumnName="id")}
     *      )
     */
    private $tags;





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

    public function existTag(models\Tag $tag)
    {
        foreach($this->tags as $temp)
        {
            if ( $tag->getID() === $temp->getId() )
                return true;
        }
        return false;
    }

    public function addTag(models\Tag $tag)
    {
        if ( !$this->existTag($tag) );
            $this->tags->add($tag);
    }


    public function getId(){ return $this->id; }
    public function getBody(){ return $this->body; }
    public function getTags(){ return $this->tags; }

    public function setId($id){ $this->id = $id; }
    public function setBody($body){ $this->body = $body; }
    public function setTags($tags){ $this->tags = $tags; }

}

最后,使用的连接表是“entry_tagged”,看起来像这样:

entry_id | tag_id

关于Symfony2 : ManyToMany relation and Collection form type,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10832730/

相关文章:

php - 如何与 Hateoas PHP 库中的组一起工作?

symfony - 如何更改条令标准中的命令顺序

symfony - doctrine2 按带有 ids 的数组排序

php - Symfony5 项目的 Phan/phan 配置

dependency-injection - Symfony 服务严格参数

php - Composer 更新后来自命名空间 "Predis\Profile"的 SncRedisExtension Factory 中的 ClassNotFoundException

php - Doctrine 2 ManyToOne 映射注解

php - 如何更改 Symfony 2 中的默认 EntityRepository 基类?

php - Symfony 3 中 FilesystemAdapter 的默认缓存目录在哪里?

php - 无法在 symfony2 控制台命令中保留对象