Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Doctrine2 Flush a Single Removed Entity

Trying to remove an entity, without persisting other changes. Note that (while in this specific situation it's not really needed) the method should not effect the outcome of a flush() called after the action.

$em->remove($entity);
$em->flush($entity);

That throws an 'InvalidArgumentException' with message 'Entity has to be managed for single computation.

I can just use DQL to do the remove; just was wondering if there's a way to do it through the entity manager.

like image 915
Tim Lytle Avatar asked Dec 14 '12 22:12

Tim Lytle


3 Answers

I forgot about transactions, which I'll have to test:

// $em instanceof EntityManager
$em->transactional(function($em) {
    $em->remove($entity);
});

Just not certain I can use a transaction if entities changed before and after the transaction are not in an explicit transaction.

like image 141
Tim Lytle Avatar answered Oct 13 '22 10:10

Tim Lytle


Try this one:

  1. Detach the entity from current EM:

    $em->detach($entity);  
    
  2. Create a new instance of EM and work with it to remove:

    $em2->remove($entity);
    $em2->flush();   
    

Or, you can use the method clear() that is in charge of detach all entities from the EM, like this:

$em->clear();
$em->remove($entity);
$em->flush(); 
like image 44
manix Avatar answered Oct 13 '22 12:10

manix


Simple solution is :

$entity = $em->manage($entity);
// $entity now refers to the fully managed copy returned by the merge operation.
// The EntityManager $em now manages the persistence of $entity as usual
$em->remove($entity);
$em->flush();
like image 21
Bouchehboun Saad Avatar answered Oct 13 '22 12:10

Bouchehboun Saad