doctrine 2从关系数组集合中删除对象

时间:2011-07-18 15:17:58

标签: zend-framework doctrine doctrine-orm

class Lists extends \Entities\AbstractEntity {

    /**
     * @Id @Column(name="id", type="bigint",length=15)
     * @GeneratedValue(strategy="AUTO")
     */
    protected $id;
    /**
     * @ManyToMany(targetEntity="\Entities\Users\Usercomments")
     * @JoinColumn(name="id", referencedColumnName="id")
     */
    protected $comments;

    public function getComments() {
        return $this->comments;
    }
    public function addComments($comment) {
        $this->comments->add($comment);
    }
    public function deleteComments(\Entities\Users\Comments $comments) {
        $this->comments->removeElement($comments);
    }

    /** @PreUpdate */
    public function updated() {
        //$this->updated_at = new \DateTime("now");
    }

    public function __construct() {

        $this->entry = new \Doctrine\Common\Collections\ArrayCollection();

    }

}

我有一个由学说创建的多对多表格。我可以设法通过以下方式为此表添加评论:

$getList = $this->_lis->findOneBy((array('userid' => $userid)));

$getComments = $this->_doctrine->getReference('\Entities\Users\Comments', $commentid);

$getList->addComments($getComments);
$this->_doctrine->flush();

但我不能删除... 我试过:removeElement但没有快乐.. 有人告诉我,我可以在我的阵列集合中解开soemthing,我不明白......

1 个答案:

答案 0 :(得分:-1)

你可以使用一个简单的PHP" unset()"在ArrayCollection元素上。最好的方法是在Entity类中定义一个新方法。

这是一个从ArrayCollection属性中删除所有元素的示例:

/**
 * Goes into your Entity class
 * Refers to property Entity::widget
 * @return $this
 */
public function removeAllWidgets()
{
    if ($this->widget) {
        foreach ($this->widget as $key => $value) {
            unset($this->widget[$key]);
        }
    }
    return $this;
}

您可能还可以定义一个Entity方法来删除单个元素:

/**
 * Goes into your Entity class
 * @param int $elementId
 * @return $this
 */
public function removeOnewidget($elementId)
{
    if (isset($this->widget[$elementId])) {
        unset($this->widget[$elementId]);
    }
    return $this;
}