在使用Symfony2和Doctrine2插入另一个表后试图更新一个表

问题描述:

我在BudgetRepository中编写了一个函数,这个函数在向预算表插入新数据时被调用。该功能是:在使用Symfony2和Doctrine2插入另一个表后试图更新一个表

public function addBudgetToClient($clientId, $budgetId) 
{ 
    return $this->createQueryBuilder('b') 
       ->update('PanelBundle:Client', 'c') 
       ->set('c.budget', $budgetId) 
       ->where('c.id = ' . $clientId) 
       ->getQuery() 
       ->execute(); 
} 

而且BudgetController做到这一点:

public function addAction(Request $request) 
{ 
    $form = $this->createForm(new BudgetType()); 
    $manager = $this->getDoctrine()->getManager(); 
    $Budget = $manager->getRepository('PanelBundle:Budget'); 
    $Client = $manager->getRepository('PanelBundle:Client'); 

    if ($request->getMethod() == 'POST') { 
     $form->handleRequest($request); 

     if ($form->isValid()) { 
      $manager->persist($form->getData()); 
      $manager->flush(); 
      // Here's the method: 
      $Budget->addBudgetToClient($form['client_id']->getData()->getId(), $Budget->getLastId()); 

      // 
      $this->addFlash('success', 'Novo orçamento adicionado'); 

      return $this->redirect($this->generateUrl('panel_budgets')); 
     } 
    } 

    return $this->render('PanelBundle:Budget:add.html.twig', array(
     'clients' => $Client->findAll(), 
     'form' => $form->createView() 
    )); 
} 

我测试了两种输出,getLastId也是一个自定义函数,我写来从预算中最大的ID,和$form['client_id']->getData()->getId()也检索客户端ID。我猜Symfony2会自动执行某些操作,因为Budget和Client是相关的,甚至保存客户端ID,在数据库中显示客户端名称,我不明白实际情况。

这里的问题是这些错误:

[Semantical Error] line 0, col 34 near 'budget = 4 WHERE': Error: Invalid PathExpression. StateFieldPathExpression or SingleValuedAssociationField expected.

[2/2] QueryException: [Semantical Error] line 0, col 34 near 'budget = 4 WHERE': Error: Invalid PathExpression. StateFieldPathExpression or SingleValuedAssociationField expected. +

[1/2] QueryException: UPDATE PanelBundle:Client c SET c.budget = 4 WHERE c.id = 1 +

我发现有关此异常的许多问题,但他们并没有与update功能,只有select了吧。

+0

你不应该直接操纵id,让教条为你做。 – kormik

+0

@kormik您的意思是检索预算ID?我想有更好的办法。我怎么做? – mfgabriel92

您不应该使用queryBuilder为这种情况构建更新查询。使用OOP方法更新您的实体。

if ($form->isValid()) { 
    $budgetEntity = $form->getData(); 
    $manager->persist($budgetEntity); 
    $clientEntity = $Budget->find($form['client_id']->getData()->getId()); 
    $clientEntity->setBudget($budgetEntity); 

    $manager->flush(); 
    $this->addFlash('success', 'Novo orçamento adicionado'); 

    return $this->redirect($this->generateUrl('panel_budgets')); 
} 
+0

谢谢,错误消失了,但'$ clientEntity'返回NULL。 – mfgabriel92