Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete records in Doctrine

Tags:

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?

like image 636
Hassan Sardar Avatar asked Oct 23 '13 11:10

Hassan Sardar


2 Answers

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.

like image 132
Ramy Nasr Avatar answered Oct 13 '22 13:10

Ramy Nasr


For my understanding if you need to delete a record in doctrine that have a doctrine relationship eg. OneToMany, ManyToMany and association cannot be easy deleted until you set the field that reference to another relation equal to null.

......

you can use this for non relation doctrine

  $entityManager=$this->getDoctrine()->getManager();  $single_user=$this->getDoctrine()->getRepository(User::class)->findOneBy(['id'=>$id]);      $entityManager->remove($single_user);      $entityManager->flush();                         

but for relation doctrine set the field that reference to another relation to null

$entityManager=$this->getDoctrine()->getManager();      $single_user=$this->getDoctrine()->getRepository(User::class)->findOneBy(['id'=>$id]);      {# assume you have field that reference #}                $single_user->setFieldData(null);         $entityManager->remove($single_user);      $entityManager->flush(); 
like image 34
l4f2s4 Avatar answered Oct 13 '22 11:10

l4f2s4