开发者

doctrine 2 remove object from relationship array collection

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();

    }

}

i have a many to many table create by doctrine.. i can manage to add comments to this table by:

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

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

$getList->addCom开发者_高级运维ments($getComments);
$this->_doctrine->flush();

but i cant delete... i tried: removeElement but no joy.. someone told me that i can unset soemthing in my array collection, i dont get it...


You can use a simple PHP "unset()" on the ArrayCollection element. Best place to do this would be to define a new method in your Entity class.

Here is an example which removes all elements from an ArrayCollection property:

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

You could probably also define an Entity method to remove a single element:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜