Hello everyone!

We have been investing plenty of personal time and energy for many years to share our knowledge with you all. However, we now need your help to keep this blog running. All you have to do is just click one of the adverts on the site, otherwise it will sadly be taken down due to hosting etc. costs. Thank you.

Example below shows you how to use entity manager and doctrine repository for CRUD operations in symfony applications. Note: You can either use getManager() or getEntityManager().


Create


$em = $this->getDoctrine()->getEntityManager();
$person->setName('inanzzz');
$em->persist($person);
$em->flush();

Read


$repo = $this->getDoctrine()->getRepository('MyUserBundle:Person');
$person = $repo->findOneBy(['id' => $personId]);

Update


$em = $this->getDoctrine()->getEntityManager();
$repo = $em->getDoctrine()->getRepository('MyUserBundle:Person');
$person = $repo->findOneBy(['id' => $personId]);
$person->setName('inanzzz');
$em->flush();

Delete


$em = $this->getDoctrine()->getEntityManager();
$repo = $em->getDoctrine()->getRepository('MyUserBundle:Person');
$person = $repo->findOneBy(['id' => $personId]);
$em->remove($person);
$em->flush();