实体如何持久两次?

时间:2019-02-04 12:01:10

标签: symfony doctrine-orm

我有一个奇怪的问题:我的两个实体随机两次被持久保存。 让我解释 : 我有一个实体项目,该实体项目具有与Transaction的ManyToOne关系。一个项目还与客户有一个ManyToOne关系。 这是导致问题的代码:

        $transaction = new TransactionBuyer();

        if ($fees) {
            $option = new TransactionOptions();
            //setters 
            $em->persist($option);
        }

        $warrantyOption = new TransactionOptions();
        //other setters
        $deposit = new Deposit();
        // setters

        $transaction->setCustomer($customer);
        $transaction->setAd($ad);
        $transaction->setDeliveryMode($deliveryMode);
        $transaction->setDeposit($deposit);

        $ad->setStatus(AdStatus::AD_PENDING_SELL);
        $project = new CustomerProjectBuy();
        $project->setCustomer($customer);
        $project->setTransactionBuyer($transaction);
        $project->setTransactionSeller($transactionSeller);
        $project->setPromoCode($promoCode);
        $ad->getCar()->addCustomerProject($project);


        $transactionSeller->addProject($project);
        foreach ($transactionSeller->getProjects() as $project) {
            if ($project instanceof CustomerProjectSell) {
                $project->setTransactionBuyer($transaction);
            }
        }
        $customer->addProject($project);
        $transaction->addProject($project);
        $customer->setTermsOfSaleAccepted(true);

        $projectSell = $em->getRepository('CoreBundle:CustomerProjectSell')->findOneBy(['car' => $ad->getCar(), 'transactionSeller' => $transactionSeller]);
        $projectSell->setTransactionBuyer($transaction);

        $em->persist($deposit);
        $em->persist($transaction);
        $em->persist($warrantyOption);
        $em->persist($project);
        $em->flush();

交易和项目被两次保留了两次(例如三分之一)。这两个实体包含相同的数据。 我无法在本地环境中重现该问题。 最近我在生产中遇到了这个问题:

An exception occurred while executing 'UPDATE Ad SET `Status` = ?, LastUpdateDate = ? WHERE id = ?' with params [5, "2019-02-04 12:01:10", 6098]:

SQLSTATE[40001]: Serialization failure: 1213 Deadlock found when trying to get lock; try restarting transaction

此异常发生在刷新时。可以链接吗?

1 个答案:

答案 0 :(得分:0)

请勿保留您的子实体,只需将其子实体设置为其父实体,而仅保留您的主实体。

如果我们将项目视为主要实体,则应仅按以下说明进行保存。 $em->persist($project);

阅读以下文章,了解逐步指南。 https://symfonycasts.com/screencast/symfony3-doctrine-relations/save-relation#