ladone
ladone

Reputation: 112

Dont work "remove" in Doctrine2

Why I can't delete entry in database using Doctrine 2 Entity manager? I have next controller and entity with whom I have a problem. I get in controller object form entity manager and i can't delete this object. Why?

// /Controller/Controller.php
/**
 * Handler delete checkbox
 * @Route("/administrator/services/delete/{id}", requirements={"id" = "\d+"}, defaults={"id" = 0}, name="service_delete")
 * @Template()
 */
public function serviceDeleteAction(Request $request, $id){
    $em = $this->getDoctrine()->getEntityManager();
    $repoServices = $em->getRepository(CoworkingService::class);

    $services = $repoServices->findOneBy(['id' => $id]);
    $em->remove($services);
    $em->persist($services);
    $em->flush();

    return [];//$this->redirectToRoute('administrator');
}

// /Entity/CoworkingService.php
class CoworkingService
{
/**
 * @ORM\Id
 * @ORM\Column(type="integer")
 * @ORM\GeneratedValue(strategy="AUTO")
 */
private $id;

/**
 * @ORM\Column(type="string", length=50)
 */
private $name;

/**
 * @ORM\ManyToOne(targetEntity="SentviBundle\Entity\Language")
 * @ORM\JoinColumn(name="language_id", referencedColumnName="id", onDelete="CASCADE")
 */
private $language;

/**
 * @ORM\Column(name="common_identifier", type="text")
 */
private $commonIdentifier;

Thanks!

Upvotes: 0

Views: 2224

Answers (1)

lxg
lxg

Reputation: 13127

@Matteo’s comment has already solved the issue, but let me explain what has happened.

You’re executing 3 entity manager operations:

$em->remove($services);
$em->persist($services);
$em->flush();

You must know that, before you call $em->flush(), all operations are registered in a service called the “unit of work” (UOW).

The UOW keeps track of all modifications in your entities (including adding/deleting entities), and only applies them to the database when you call flush().

When calling $em->remove($services), you told the UOW that you want to delete the entity. However, when calling $em->persist($services) directly afterwards, you told the UOW that you want to create (or, effectively: keep) the entity. (Note that, in Doctrine, “persist” doesn’t mean that a connection is made to the database, but instead, you pass an entity to the EM/UOW to calculate the modifications.)

So, in conclusion, the persist operation cancelled the remove out, and, at that point, flush had nothing to do.

For more details on the entity lifecycle and EM states see http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/working-with-objects.html

Upvotes: 4

Related Questions