em->getConnection(); $conn->beginTransaction(); try { $queries = [ ...$this->updateReferences($toKeep, $toDelete), ...$this->removeThirdparty($toKeep, $toDelete), ]; foreach ($queries as $query) { $conn->executeStatement($query['sql'], $query['params']); } $conn->commit(); } catch (\Exception $e) { $conn->rollBack(); throw $e; } } private function updateReferences(ThirdParty $toKeep, ThirdParty $toDelete): array { $queries = []; $allMeta = $this->em->getMetadataFactory()->getAllMetadata(); foreach ($allMeta as $meta) { if ($meta->isMappedSuperclass) { continue; } $tableName = $meta->getTableName(); foreach ($meta->getAssociationMappings() as $assoc) { if (ThirdParty::class !== $assoc['targetEntity']) { continue; } // phpstan wants boolean for if condition if (($assoc['type'] & ClassMetadata::TO_ONE) !== 0) { $joinColumn = $meta->getSingleAssociationJoinColumnName($assoc['fieldName']); $suffix = (ThirdParty::class === $assoc['sourceEntity']) ? 'chill_3party.' : ''; $queries[] = [ 'sql' => "UPDATE {$suffix}{$tableName} SET {$joinColumn} = :toKeep WHERE {$joinColumn} = :toDelete", 'params' => ['toKeep' => $toKeep->getId(), 'toDelete' => $toDelete->getId()], ]; } elseif (ClassMetadata::MANY_TO_MANY === $assoc['type'] && isset($assoc['joinTable'])) { $joinTable = $assoc['joinTable']['name']; $prefix = null !== ($assoc['joinTable']['schema'] ?? null) ? $assoc['joinTable']['schema'].'.' : ''; $joinColumn = $assoc['joinTable']['inverseJoinColumns'][0]['name']; $queries[] = [ 'sql' => "UPDATE {$prefix}{$joinTable} SET {$joinColumn} = :toKeep WHERE {$joinColumn} = :toDelete AND NOT EXISTS (SELECT 1 FROM {$prefix}{$joinTable} WHERE {$joinColumn} = :toKeep)", 'params' => ['toDelete' => $toDelete->getId(), 'toKeep' => $toKeep->getId()], ]; $queries[] = [ 'sql' => "DELETE FROM {$joinTable} WHERE {$joinColumn} = :toDelete", 'params' => ['toDelete' => $toDelete->getId()], ]; } } } return $queries; } public function removeThirdparty(ThirdParty $toKeep, ThirdParty $toDelete): array { return [ [ 'sql' => 'UPDATE chill_3party.third_party SET parent_id = :toKeep WHERE parent_id = :toDelete', 'params' => ['toKeep' => $toKeep->getId(), 'toDelete' => $toDelete->getId()], ], [ 'sql' => 'UPDATE chill_3party.thirdparty_category SET thirdparty_id = :toKeep WHERE thirdparty_id = :toDelete AND NOT EXISTS (SELECT 1 FROM chill_3party.thirdparty_category WHERE thirdparty_id = :toKeep)', 'params' => ['toKeep' => $toKeep->getId(), 'toDelete' => $toDelete->getId()], ], [ 'sql' => 'DELETE FROM chill_3party.third_party WHERE id = :toDelete', 'params' => ['toDelete' => $toDelete->getId()], ], ]; } }