getConnection(); $createdPaths = []; try { return $connection->transaction(function () use ( $ticketId, $actorId, $content, $status, $request, $ownerId, &$createdPaths ) { // This query must be inside the transaction. A lock acquired // in autocommit mode would be released before the reply save. $query = Ticket::where('id', $ticketId)->where('rootid', 0); if ($ownerId !== null) { $query->where('userid', $ownerId); } $root = $query->lockForUpdate()->first(); if ($root === null) { return null; } $event = $status === 1 && (int) $root->status !== 1 ? '工单重新开启' : '用户回复工单'; $reply = new Ticket(); $reply->title = (string) $root->title; $reply->content = $content; $reply->rootid = (int) $root->id; $reply->userid = $actorId; $reply->datetime = time(); $reply->status = $status; $reply->ticket_type = (string) $root->ticket_type; $reply->priority = (string) $root->priority; $reply->instance_id = $root->instance_id; $root->status = $status; if (!$root->save() || !$reply->save()) { throw new \RuntimeException('工单回复保存失败'); } // Keep attachment rows in this transaction. The service also // records every newly-created path for commit-failure cleanup. $attachments = TicketAttachmentService::store( $request, (int) $root->id, (int) $reply->id, $actorId, $createdPaths ); return [ 'root' => $root, 'reply' => $reply, 'event' => $event, 'attachments' => $attachments, ]; }, 1); } catch (\Throwable $exception) { // The DB transaction has already rolled back (or failed to // commit) when control reaches here. Only remove files created by // this request; never delete pre-existing ticket attachments. TicketAttachmentService::discardPaths($createdPaths); throw $exception; } } }