![](/img/trans.png)
[英]Symfony2, Doctrine2 update row without ID (this table is with only “one” row)
[英]Trying to update one table after inserting into another one with Symfony2 and Doctrine2
我在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
也是我編寫的自定義函數,用於從Budget中檢索最大的ID,而$form['client_id']->getData()->getId()
也會檢索Client ID。 我猜Symfony2會自動執行某項操作,因為預算和客戶端是相關的,甚至保存了客戶端ID,但在數據庫中顯示了客戶端名稱,我不知道實際上是怎么做的。
這里的問題是這些錯誤:
[語義錯誤]第0行,“預算= 4 WHERE”附近的第34列:錯誤:無效的PathExpression。 預期為StateFieldPathExpression或SingleValuedAssociationField。
[2/2] QueryException:[語義錯誤]第0行,'預算= 4 WHERE'附近的第34列:錯誤:無效的PathExpression。 預期為StateFieldPathExpression或SingleValuedAssociationField。 +
[1/2] QueryException:更新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'));
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.