doctrine2 在数据库中插入 arraycollection

doctrine2 insert arraycollection in database

我正在尝试在我的数据库中插入一个数组集合。对象之间的关系是 ManyToMany 。所以我想 post 一条消息并添加一些标签(不只是一个,一些例如存储在 Doctrine 2 数组集合中)。没有错误,但是对象没有被link编辑:(table的messageshastags都包含数据,但是messages_hastagstable 为空。

我的代码:

Message.php

/**
 * @ORM\ManyToMany(targetEntity="Application\Entity\Hashtag", mappedBy="messages")
 */
private $hashtags;

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

function getHashtags() {
    return $this->hashtags;
}

function setHashtags($hashtags) {
    $this->hashtags = $hashtags;
}

Hashtag.php

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

/** @ORM\ManyToMany(targetEntity="Application\Entity\Message", inversedBy="hashtags") */
private $messages;

function getMessages() {
    return $this->messages;
}

function setMessages($messages) {
    $this->messages = $messages;
}

Controller.php

$hashtag_array = new \Doctrine\Common\Collections\ArrayCollection(); 
$hashtag_array->add(HASHTAG); //here is a for loop adding some entities

$newMessage = \Application\Entity\Message();
$newMessage->setHashtags($hashtag_array);
$em->persist($newMessage);
$em->flush();

该消息将出现在数据库中,但主题标签没有 link。

你的映射严重错误。 inversedBymappedBy 字段都指向 "hashtags"。其中一个甚至有错字(hastags)。

在您的留言中应该是mappedBy="messages"
您还需要始终 initialize your collections in the constructor!

因此在 Hashtag 实体内部:

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

我建议先解决所有这些问题,然后检查您的问题是否已解决。

更新

你不能这样做:

$newMessage->setHashtags($hashtag_array);

Doctrine 集合不能直接与这样的数组交换。 您必须添加 setter 和 getter 方法,如 the Doctrine 2 documentation chapter 8. Working with Associations 中所写。我建议您在继续使用 Doctrine 之前阅读一些文档。为了使这些事情起作用,了解 Doctrine 的内部结构很重要。

这是您的 Message 资源中的样子:

/**
 * Get hashtags
 *
 * @return Collection
 */
public function getHashtags()
{
    return $this->hashtags;
}

/**
 * Add hashtag.
 *
 * @param Hashtag $hashtag
 * @return self
 */
public function addHashtag(Hashtag $hashtag)
{
    $this->hashtags->add($hashtag);
    return $this;
}

/**
 * Add hashtags.
 *
 * @param Collection|array $hashtags
 * @return self
 */
public function addHashtags($hashtags)
{
    foreach($hashtags as $hashtag){
        $this->addHashtag($hashtag);
    }
    return $this;
}

/**
 * Remove hashtag.
 *
 * @param Hashtag $hashtag
 * @return self
 */
public function removeHashtag(Hashtag $hashtag)
{
    $this->hashtags->removeElement($hashtag);
    return $this;
}

/**
 * Remove hashtags.
 *
 * @param Collection|array $hashtags
 * @return self
 */
public function removeHashtags($hashtags)
{
    foreach($hashtags as $hashtag){
        $this->removeHashtag($hashtag);
    }
    return $this;
}