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


Trying to update one table after inserting into another one with Symfony2 and Doctrine2

我在BudgetRepository中编写了一个函数,该函数在向预算表插入新数据时调用。函数是:

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自动做一些事情,因为预算和客户端是相关的,甚至保存客户端id,在数据库中显示客户端名称,我不明白实际上如何。

问题是这些错误:

[语义错误]第0行,col 34接近'budget = 4 WHERE':错误:Invalid patheexpression。

StateFieldPathExpression或SingleValuedAssociationField。

[2/2] QueryException:[语义错误]line 0, col 34 near 'budget = 4 WHERE':错误:Invalid patheexpression。statefieldpatheexpression或SingleValuedAssociationField。+

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

我发现这个异常有很多问题,但是他们没有update函数,只有select

您不应该使用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'));
}