尝试使用Symfony2和Doctrine2

时间:2015-09-07 15:04:14

标签: php symfony orm doctrine-orm query-builder

我在BudgetRepository中编写了一个函数,在将新数据插入Budget表时调用该函数。功能是:

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,在数据库中显示客户端名称,我实际上并不了解。

这里的问题是这些错误:

  

[语义错误]第0行,第34行附近'budget = 4 WHERE':错误:无效的PathExpression。期望StateFieldPathExpression或SingleValuedAssociationField。

     

[2/2] QueryException:[语义错误]第0行,第34行靠近'budget = 4 WHERE':错误:无效的PathExpression。期望StateFieldPathExpression或SingleValuedAssociationField。 +

     

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

我发现此异常存在许多问题,但他们没有使用update函数,只有select

1 个答案:

答案 0 :(得分:0)

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