我在两个实体(ClientProject& Tour)之间有一个ManyToMany关系,除了一个案例之外,它实际上正在工作。当我想清除这些实体之间的所有关系时,它不起作用,数据库也不会相应地更新。
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);
}
Tour.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(),
]);
}
答案 0 :(得分:0)
为了使删除工作正常,我认为您需要将此代码添加到删除方法中:
# 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"}
设置关系时。