在postRemove或preRemove

时间:2018-11-22 16:05:12

标签: php symfony doctrine

上下文

我目前有一个实体Request,其中有Approval个实体的集合。

我的目标是一旦将批准从Request中删除后,将它们存档。

我尝试使用@preRemove@postRemove使它在事件监听器中工作(尽管在postRemove事件中在数据库中工作是一种不好的做法,但是我为此尝试了。)

问题

但是除非我只有1条记录要存档,否则我无法使它们在任何一个中都不能工作。一旦我有2条记录,它将引发异常。

@postRemove例外-尝试两次删除相同的Approval

  

通知:未定义索引:0000000061b600620000000079e76cab

@preRemove例外-尝试保留空的ArchivedApproval

  

执行'INSERT INTO tblArchivedApprovals([Level],RequestedOn,ApprovalStatus,ApproverComments,ApprovedOn,ApprovedAmount,ApproverID,RequestedBy,ApprovedBy,DeductionID)值时发生异常(?,?,?,?,?,?,? ,?,?,?)':

     

SQLSTATE [07002,0]:[Microsoft] [SQL Server的ODBC驱动程序17] COUNT字段不正确或语法错误

@preRemove查询:

INSERT INTO tblArchivedApprovals
    ([Level], RequestedOn, ApprovalStatus, ApproverComments, ApprovedOn, ApprovedAmount, ApproverID, RequestedBy, ApprovedBy, DeductionID)
VALUES
    (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)

Parameters: []

任何关于如何执行此操作的想法将不胜感激。

编辑::这是所请求的侦听器类:

<?php

namespace App\Entity\EventListener;

use App\Entity\Approval;
use App\Entity\ArchivedApproval;
use Doctrine\ORM\EntityManager;
use Doctrine\ORM\Event\LifecycleEventArgs;
use Doctrine\ORM\Mapping as ORM;

class ApprovalListener
{

    /**
     * Archive the approval(s) to the approval history before removing them
     *
     * @ORM\PostRemove
     *
     * @param Approval $approval
     * @param LifecycleEventArgs $event
     *
     * @return void
     * @throws \Doctrine\ORM\ORMException
     */
    public function postRemove(Approval $approval, LifecycleEventArgs $event): void
    {
        // Create and set values
        $archivedApproval = new ArchivedApproval();
        $archivedApproval->setDeductionRequest($approval->getDeductionRequest());
        $archivedApproval->setRequestedOn($approval->getRequestedOn());
        $archivedApproval->setRequestedBy($approval->getRequestedBy());
        $archivedApproval->setApprover($approval->getApprover());
        $archivedApproval->setLevel($approval->getLevel());

        if (null !== $approval->getStatus()) {
            $archivedApproval->setStatus($approval->getStatus());
            $archivedApproval->setApproverComments($approval->getApproverComments());
            $archivedApproval->setApprovedAmount($approval->getApprovedAmount());
            $archivedApproval->setApprovedBy($approval->getApprovedBy());
            $archivedApproval->setApprovedOn($approval->getApprovedOn());
        }

        // Save the approval history
        /** @var EntityManager $em */
        $em = $event->getEntityManager();
        $em->persist($archivedApproval);
        $em->flush($archivedApproval);
    }

}

1 个答案:

答案 0 :(得分:0)

当前解决方案(并非最佳)

到目前为止,我唯一的方法是将ArchivedApproval实体添加到Request实体的removeApproval函数中,但是我必须遍历批准并逐个删除它们而不是简单地调用$request->getApprovals()->clear();