我在两个实体(ClientProject 和 Tour)之间有一个多对多关系,除了一种情况外,该关系实际上正在工作。当我想清除这些实体之间的所有关系时,它不起作用并且数据库不会相应更新。
ClientProject.php
/**
* @ORM\ManyToMany(targetEntity="Tour", inversedBy="clientProjects")
* @ORM\JoinTable(
* name="client_projects_tour_items",
* joinColumns={
* @ORM\JoinColumn(name="client_project_id", referencedColumnName="id")
* },
* inverseJoinColumns={
* @ORM\JoinColumn(name="tour_id", referencedColumnName="id")
* }
* )
*/
protected $tourItems;
public function removeTourItem(\SharedBundle\Entity\Tour $tourItem)
{
$this->tourItems->removeElement($tourItem);
}
旅游.php
public function removeClientProject(\SharedBundle\Entity\ClientProject $clientProject)
{
$this->clientProjects->removeElement($clientProject);
}
工作示例:
失败示例:
控制器动作
public function editClientProjectAction($id, Request $request)
{
if (!$request->isXmlHttpRequest()) {
return $this->redirectToRoute('contact');
}
$clientProject = $this->getDoctrine()->getRepository(ClientProject::class)->find($id);
if(!$clientProject) {
return new JsonResponse(array('redirect' => $this->generateUrl('contacts')));
}
$form = $this->createForm(ClientProjectFormType::class, $clientProject, array(
'action' => $this->generateUrl('edit-client-project', array('id' => $id))
));
$form->setData($clientProject);
if ($request->isMethod('POST')) {
$form->submit($request->request->get($form->getName()), false);
if($form->isSubmitted() && $form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($clientProject);
$em->flush();
return new JsonResponse(array('reloadDatatable' => 'client_project_datatable'));
} else {
return new JsonResponse(array('reload' => true));
}
}
return $this->render('@AppBundle/client-projects/edit-client-project.html.twig', [
'form' => $form->createView(),
]);
}
为了使删除工作,我认为您需要将此代码添加到您的删除方法中:
# Entity/ClientProject.php
/**
* Remove tourItem
*
* @param \SharedBundle\Entity\Tour $tourItem
*/
public function removeTourItem(\SharedBundle\Entity\Tour $tourItem)
{
if (!$this->tourItems->contains($tourItem)) {
return;
}
$this->tourItems->removeElement($tourItem);
$clientProject->removeTourItem($this);
}
# Entity/Tour.php
/**
* Remove clientProject
*
* @param \SharedBundle\Entity\ClientProject $clientProject
*/
public function removeClientProject(\SharedBundle\Entity\ClientProject $clientProject)
{
if (!$this->clientProject->contains($clientProject)) {
return;
}
$this->clientProjects->removeElement($clientProject);
$tourItem->removeClientProject($this);
}
另外,在
Tour.php
文件中,您需要添加此注释:
cascade={"persist", "remove"}
当您建立关系时。
尽管这是一个老问题,但我想我会根据需要添加答案。
要删除多对多关系中的所有关联,您可以在集合上调用
->clear()
。
假设
getTourItems()
返回 PersistentCollection
对象:
$clientProject->getTourItems()->clear();
$entityManager->flush();