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 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度