P
P
Pavel Novikov2018-06-13 13:04:00
MySQL
Pavel Novikov, 2018-06-13 13:04:00

How to properly rollBack a Doctrine transaction?

I have a code that inserts data into multiple tables in turn, which looks like this:

$em->getConnection()->beginTransaction();

                try {
                    $em->flush();

                    try {
                        /** @var \AppBundle\Entity\Warehouse $warehouse */
                        $warehouse = $this->warehouseRepository->getRepository()->findOneBy([
                            'boxType' => $boxType,
                            'status' => Warehouse::STATUS_FREE
                        ]);

                        $oldStatus = $warehouse->getStatus();
                        $warehouse->setStatus(Warehouse::STATUS_BUSY);

                        $this->warehouseStatusManager->change($warehouse, $oldStatus);
                        $em->flush();

                        try {
                            $order = new Order();
                            $order->setUser($this->getUser());
                            $order->addWarehouse($warehouse);
                            $order->setRentFrom(\DateTime::createFromFormat('d/m/Y', $formData['rentFrom']));

                            $em->persist($order);
                            $em->flush();
                            $em->getConnection()->commit();
                            return Response::create('ok');
                        } catch (\Exception $exception) {
                            return Response::create('Can not save order. Aborted');
                        }
                    } catch (\Exception $exception) {
                        return Response::create('Can not proceed warehouse data');
                    }
                } catch (\Exception $exception) {
                    $em->getConnection()->rollBack();
                    return Response::create('Can not save address');
                }

the question is, do I need to execute the `$em->getConnection()->rollBack();` method in every tri-catch block, or is the way I did enough?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question