Symfony2在UPDATE查询后获取新值

时间:2016-09-25 19:51:04

标签: php symfony doctrine-orm

在我的Symfony2.8应用程序中,我得到了以下控制器:

public function changetariffAction(Request $request)
{
    $em = $this->getDoctrine()->getManager();
    $user = $this->container->get('security.context')->getToken()->getUser();
    $userid = $user->getId();
    $tariff = $user->getTariff();//tariff1 here

    $paymentForm = $this->createPaymentForm($user);
    $paymentForm->handleRequest($request);

    if($tariff != 'tariff2') {

        $query = $em->createQuery('UPDATE My\UserBundle\Entity\User u SET u.tariff = :tariff2 WHERE u.id = :userid');
        $query->setParameter('userid', $user->getId());
        $query->setParameter('tariff2', 'tariff2');
        $query = $query->getResult();//returns 1 here, tariff field in DB is set to tariff2 as expected

        $query = $em->createQuery('SELECT u FROM My\UserBundle\Entity\User u WHERE u.id = :userid');//getting once again user entity but it did not change
        $query->setParameter('userid', $user->getId());
        $user = $query->getResult();

        $tariff_upd = $user[0]->getTariff();//tariff1 here but I need tariff2! 
//Also I tried to persist and flush user entity here but it did not work
        return $this->render('MyBundle:Pages:tariffchangesuccess.html.twig', array(
        'user' => $user,
        'form' => $paymentForm->createView(),
        'tariff' => $tariff_upd //still tariff1 but I need tariff2 
    ));

    }
    return $this->render('MyBundle:Pages:tariffchangesuccess.html.twig', array(
        'user' => $user,
        'form' => $paymentForm->createView(),
        'tariff' => $tariff
        ));

}

我的控制器工作正常,所有值都在我的数据库中按预期更新,但新值(关税2)不会在我的树枝模板中呈现。仅当我在浏览器中更新页面时才会呈现新值(按F5),但这不是预期的行为。任何想法如何解决?谢谢。

2 个答案:

答案 0 :(得分:3)

Doctrine使用与缓存类似的东西,也许您使用查询而不是本机方法会使此系统短路。 Docrtine可以处理你的实体并知道要记录什么和已经改变等等。但是你必须使用Doctrine函数或存储库,而不是通过自定义查询来实现...... Doctrine方式应该是这样的:

$em = $this->getDoctrine()->getManager();
$userid = $this->container->get('security.context')->getToken()->getUser()->getId()
// Get object user from DB values
$user = $em->getRepository('My\UserBundle:User')->findOneById($userid );
// Update tarif in the user object
$user->setTariff('tariff2');
// Let Doctrine write in the DB. The persist() may not be necesary as Doctrine already manage this object, but it's a good practise.
$em->persist($user);
$em-> flush();
// Doctrine should already have update the $user object, but if you really really want to be sure, you can reload it:
$user = $em->getRepository('My\UserBundle:User')->findOneById($userid );

答案 1 :(得分:2)

您可以使用refresh的{​​{1}}方法,以便:

  

从数据库刷新实体的持久状态,   覆盖尚未保留的任何本地更改。

所以添加刷新调用,例如:

EntityManager

希望这个帮助