Doctrine ODM - Clear / update / remove EmbedDocument relations

Question!

I'm experiencing a problem with Doctrine ODM. When I create an entity with a simple EmbedMany relationship to another document (i.e. a nickpage with many comments as embedded documents), and I try to clear the collection, the collection still exists with all elements:

/** @Document */
class Nickpage
{
   ...

   /** @EmbedMany(targetDocument="Comment") */
   protected $comments = array();

   ...

   public function clearComments()
   {
      $this->comments = array();
      // or:
      // $this->comments = new \Doctrine\Common\Collections\ArrayCollection();
      return $this;
   }
}

When I simply load a nickpage with the associated comments, and I call

$nickpage->clearComments();
$dm->persist($nickpage);
$dm->flush();

the comments still exist. The same phenomenon occurs when I delete some elements in the ArrayCollection $comments and I flush...

Am I on the wrong way with handling such relationships (i.e. use ReferenceMany) or is it the wrong way to work with the references?

Greetz from Germany, Andi



Answers

You don't have to call persist because your page is already managed by Doctrine. You only have to call flush to push the update in the database.

And you don't need to add a clearComments method. You can use the clear method of the ArrayCollection :

$nickpage-
By : Maxence


This video can help you solving your question :)
By: admin