dspx15491 2017-02-17 20:31
浏览 14
已采纳

不要在Doctrine2中“删除”

Why I can't delete entry in database using Doctrine 2 Entity manager? I have next controller and entity with whom I have a problem. I get in controller object form entity manager and i can't delete this object. Why?

// /Controller/Controller.php
/**
 * Handler delete checkbox
 * @Route("/administrator/services/delete/{id}", requirements={"id" = "\d+"}, defaults={"id" = 0}, name="service_delete")
 * @Template()
 */
public function serviceDeleteAction(Request $request, $id){
    $em = $this->getDoctrine()->getEntityManager();
    $repoServices = $em->getRepository(CoworkingService::class);

    $services = $repoServices->findOneBy(['id' => $id]);
    $em->remove($services);
    $em->persist($services);
    $em->flush();

    return [];//$this->redirectToRoute('administrator');
}

// /Entity/CoworkingService.php
class CoworkingService
{
/**
 * @ORM\Id
 * @ORM\Column(type="integer")
 * @ORM\GeneratedValue(strategy="AUTO")
 */
private $id;

/**
 * @ORM\Column(type="string", length=50)
 */
private $name;

/**
 * @ORM\ManyToOne(targetEntity="SentviBundle\Entity\Language")
 * @ORM\JoinColumn(name="language_id", referencedColumnName="id", onDelete="CASCADE")
 */
private $language;

/**
 * @ORM\Column(name="common_identifier", type="text")
 */
private $commonIdentifier;

Thanks!

  • 写回答

1条回答 默认 最新

  • dsovc00684 2017-02-17 21:17
    关注

    @Matteo’s comment has already solved the issue, but let me explain what has happened.

    You’re executing 3 entity manager operations:

    $em->remove($services);
    $em->persist($services);
    $em->flush();
    

    You must know that, before you call $em->flush(), all operations are registered in a service called the “unit of work” (UOW).

    The UOW keeps track of all modifications in your entities (including adding/deleting entities), and only applies them to the database when you call flush().

    When calling $em->remove($services), you told the UOW that you want to delete the entity. However, when calling $em->persist($services) directly afterwards, you told the UOW that you want to create (or, effectively: keep) the entity. (Note that, in Doctrine, “persist” doesn’t mean that a connection is made to the database, but instead, you pass an entity to the EM/UOW to calculate the modifications.)

    So, in conclusion, the persist operation cancelled the remove out, and, at that point, flush had nothing to do.

    For more details on the entity lifecycle and EM states see http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/working-with-objects.html

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 请问一下这个运行结果是怎么来的
  • ¥15 这个复选框什么作用?
  • ¥15 单通道放大电路的工作原理
  • ¥30 YOLO检测微调结果p为1
  • ¥20 求快手直播间榜单匿名采集ID用户名简单能学会的
  • ¥15 DS18B20内部ADC模数转换器
  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下