Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Doctrine 2 refreshing entities after update

I would like to know if there's a way to refresh values of entities already retrieved from database, after a custom update.

An example

<?php

/**
 * Element
 *
 * @ORM\Table(name="table_element")
 */
class Element{

    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
      private $id

    /**
     *
     * @var string
     *
     * @ORM\Column(name="element_name", type="string", length=255)
     */
      private $name

      public function setName($name){
             $this->name = $name;
      }

      public function getName(){
             return $this->name;
      }

      public function getId(){
             return $this->id;
      }
}

// Inside Controller

   $em = $this->getDoctrine()->getManager();

   $element = $em->getRepository('Element')->find(1);

   // This prints "Test 1"
   echo $element->getName();

   $qb = $em->createQueryBuilder();

   $qb->update('Element', 'E')
      ->set('E.name', 'New Test Name')
      ->where('E.id = :id')
      ->setParameter('id', $element->getId()) ;

   $qb->getQuery()->execute();

   // This still prints "Test 1", i need to print "New Test Name" without using again a select
   // Something like $em->refreshManagedEntities();
   echo $element->getName();

I need to print "New Test Name" without using again a select, something like $em->persist($element); $em->refreshAllManagedEntities();

Is there a way?

P.S. I can't avoid custom queries, thiis is a semplified example of what i have to do.

like image 814
Jack Skeletron Avatar asked Dec 23 '22 21:12

Jack Skeletron


1 Answers

For this you should avoid queries and use the entity manager:

$qb = $em->createQueryBuilder();

$element = $em->getRepository('Element')->find(1);

// Prints "Test 1"
echo $element->getName();

$element->setName('New Test Name');
$em->persist($element);
$em->flush();

// Prints "New Test Name"
echo $element->getName(); 

If you have to run with queries, or if the entity alteration is done outside your script you should use refresh

   $em->refresh($entity);
like image 170
goto Avatar answered Dec 26 '22 15:12

goto