【问题标题】:doctrine 2 remove object from relationship array collection学说 2 从关系数组集合中删除对象
【发布时间】:2011-07-18 15:17:57
【问题描述】:
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();

    }

}

我有一个由学说创建的多对多表。我可以通过以下方式将 cmets 添加到该表中:

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

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

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

但我不能删除... 我试过:removeElement 但没有喜悦.. 有人告诉我,我可以在我的数组集合中取消设置某些东西,我不明白...

【问题讨论】:

  • 您使用的是哪种参考?如果它使用 ondelete 限制,您将无法删除它。
  • 你为什么要问一个问题并发布完全相反的代码?此外,请确保在构造函数中定义 $comments 的方式与使用 $entry 的方式相同。请发布示例代码并显示您的代码正在执行的 SQL。
  • 我认为你需要一个多对多连接表。

标签: zend-framework doctrine doctrine-orm


【解决方案1】:

您可以在 ArrayCollection 元素上使用简单的 PHP“unset()”。最好的方法是在您的 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;
}

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

/**
 * 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;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-26
    • 2019-02-16
    • 1970-01-01
    • 2012-05-04
    • 1970-01-01
    • 2017-03-23
    相关资源
    最近更新 更多