This forum is in READ-ONLY mode.
You can look around, but if you want to ask a new question, please use Stack Overflow.

Removing embedded documents

Other symfony projects

Removing embedded documents

by VictorTheMadVideo » Tue Mar 27, 2012 5:48 pm

Hello,

I recently started programing a simple app using DoctrineMongoDBBundle. I have two classes annotated as follow:

Code: Select all

namespace MyCompany\MyBundle\Document;

use Doctrine\ODM\MongoDB\Mapping\Annotations as MongoDB;
use Doctrine\ORM\Mapping\HasLifecycleCallbacks;

/**
 * @MongoDB\Document
 * @HasLifecycleCallbacks
 */
class Post
{
    /**
     * @MongoDB\Id
     */
    protected $id;

    /**
     * @MongoDB\EmbedMany(targetDocument="Quote")
     */
    protected $quotes = array();

    //
    //  getters, setters, ...
    //
}

/**
 * @MongoDB\EmbeddedDocument
 * @HasLifecycleCallbacks
 */
class Quote
{
    /**
     * @MongoDB\Id
     */
    protected $id;

    /**
     * @MongoDB\String
     */
    protected $text;

    //
    //  getters, setters, ...
    //
}



I need to remove a quote from a post in the deleteQuoteAction($quoteId) method of the controller, but the following does not works (throws: "InvalidArgumentException: A detached document was found through a relationship during cascading a persist operation"):

Code: Select all

public function deleteQuoteAction($quoteId)
{
  $dm = $this->get('doctrine.odm.mongodb.document_manager');
  $repository = $dm->getRepository('MyCompanyMyBundle::Quote');
  $quote = $repository->find($quoteId);
  $dm->remove($quote);
  $dm->flush();
}



The following fails too (no error, but embedded document remains into post):

Code: Select all

public function deleteQuoteAction($postId, $quoteId)
{
  $dm = $this->get('doctrine.odm.mongodb.document_manager');
  $repository = $dm->getRepository('MyCompanyMyBundle::Post');
  $post = $repository->find($postId);
  foreach ($post->getQuotes() as $quote) {
    if ($quote->getId() == $quoteId) {
      $post->getQuotes()->remove($quote);
      break;
  }
  $dm->persist($post);
  $dm->flush();
}



Any ideas about what is failing? Or any workaround using QueryBuilder?

Thanks in advance...
VictorTheMadVideo
Junior Member
 
Posts: 1
Joined: Tue Mar 27, 2012 5:19 pm