我有一个产品实体,当我添加具有多个图像的产品时,每个产品都与多个图像相关,但是如果我移除产品,则会出现错误
在删除功能中,我有以下代码:
public function delete(Request $req,Products $product){
if($this->isCsrfTokenValid('delete'. $product->getId(),$req->get('_token'))){
foreach ($product->getImages() as $image) {
$product->removeImage($image);
$this->em->remove($image);
$this->em->persist($image);
}
$this->em->remove($product);
$this->em->flush();
$this->addFlash('success',"product deleted");
}
return $this->redirectToRoute("admin.index");
}
在我进行的编辑中
public function edit(Products $product ,Request $req):Response{
$originalImages = array();
if($product){
foreach ($product->getImages() as $image) {
$originalImages[] = $image;
}
$editForm = $this->createForm(ProductsTypeForm::class,$product);
$editForm->handleRequest($req);
if($editForm->isSubmitted()&&$editForm->isValid()){
foreach ($product->getImages() as $image) {
foreach ($originalImages as $key => $toDel) {
if ($toDel->getId() === $image->getId()) {
unset($originalImages[$key]);
}
}
}
// remove the relationship between the image and the Product
foreach ($originalImages as $image) {
$product->removeImage($image);
$this->em->remove($image);
$this->em->persist($image);
}
$this->em->persist($product);
$this->em->flush();
$this->addFlash('success',"changed");
return $this->redirectToRoute('admin.index');
}
}
return $this->render('pages/admin/edit.html.twig',[
'item'=>$product,
'form'=>$editForm->createView()
]);
}
在“图像”实体中,我具有双向的多对一关系。关系已正确删除,但与产品相关的图像未删除 任何人都可以帮助我