Trying to update one table after inserting into an

2019-02-21 07:03发布

I wrote a function in BudgetRepository that is called when inserting new data into Budget table. The function is:

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

And the BudgetController does this:

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()
    ));
}

I tested both outputs, the getLastId is also a custom function I wrote to retrieve the biggest ID from Budget, and the $form['client_id']->getData()->getId() also retrieves the Client id. I guess Symfony2 automatically does something because Budget and Client are related, and even saving the Client id, in the database shows the Client name, I don't understand how actually.

The issue here are these errors:

[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 +

I found many problems about this exception but they haven't had it with update function, only select.

1条回答
爷、活的狠高调
2楼-- · 2019-02-21 07:42

You should not build an update query for this case using a queryBuilder. Use OOP approach to update your entities.

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'));
}
查看更多
登录 后发表回答