我使用:composer require annotations
然后是
public function editAction(Product $ product){
// echo '<pre>';
// print_r($product);
if(!$product){
throw $this->createNotFoundException("No product found for id:".$product->getId());
}
$product->setName('New product name!');
$product->flush();
return $this->redirectToRoute('product_show',[
'id'=>$product->getId()
]);
}
$ product对象包含Entity中的所有属性,但flush()方法被视为未定义。以下是错误消息:
Attempted to call an undefined method named "flush" of class "App\Entity\Product".
我解决了这个问题如下:
/**
* @Route("/product/edit/{id}")
*/
public function updateAction($id)
{
$em = $this->getDoctrine()->getManager();
$product = $em->getRepository(Product::class)->find($id);
if (!$product) {
throw $this->createNotFoundException(
'No product found for id '.$id
);
}
$product->setName('New product name!');
$em->flush();
return $this->redirectToRoute('product_show', [
'id' => $product->getId()
]);
}
但我想用更少的代码来做,因为我可以传递$ product对象。为什么第一种方法失败了?
N.B:我正在使用symfony4。
答案 0 :(得分:2)
您需要获取经理,并在其上调用flush,而不是直接向实体对象调用Option
像:
flush()
答案 1 :(得分:1)
在$product->setName('New product name!');
行下,请按以下代码操作:
$em->persist($product);
$em->flush();