Php – Delete records in Doctrine

doctrinedoctrine-ormPHPsymfony

I'm trying to delete a record in Doctrine, but I don't know why it's not deleting.

Here is my Code:

function del_user($id)
{
    $single_user = $entityManager->find('Users', $id);

    $entityManager->remove($single_user);

    $entityManager->flush();
}

Plus: How can I echo query to see what going on here?

Best Answer

This is an old question and doesn't seem to have an answer yet. For reference I am leaving that here for more reference. Also you can check the doctrine documentation

To delete a record, you need to ( assuming you are in your controller ):

// get EntityManager
$em = $this->getDoctrine()->getManager();

// Get a reference to the entity ( will not generate a query )
$user = $em->getReference('ProjectBundle:User', $id);

// OR you can get the entity itself ( will generate a query )
// $user = $em->getRepository('ProjectBundle:User')->find($id);

// Remove it and flush
$em->remove($user);
$em->flush();

Using the first method of getting a reference is usually better if you just want to delete the entity without checking first whether it exists or not, because it will not query the DB and will only create a proxy object that you can use to delete your entity.

If you want to make sure that this ID corresponds to a valid entity first, then the second method is better because it will query the DB for your entity before trying to delete it.

Related Topic