A transaction groups statements so they either all succeed or all fail. This keeps related changes consistent, for example when transferring a value between two records.
Transaction blocks
The simplest approach wraps statements in BEGIN TRANSACTION and COMMIT TRANSACTION and runs them as a single query with run(). SurrealDB rolls back the whole block if any statement fails. This works over both WebSocket and HTTP.
$db->run('
BEGIN TRANSACTION;
UPDATE account:one SET balance -= 100;
UPDATE account:two SET balance += 100;
COMMIT TRANSACTION;
');Use CANCEL TRANSACTION inside the block, or a THROW expression, to abort and roll back from within SurrealQL.
Explicit transaction handles
For finer control over a WebSocket connection, the ConnectionController exposes explicit transaction handles through connection(). Call begin() to start one, then commit() or cancel() with the returned handle.
$txn = $db->connection()->begin();
try {
// ... run statements bound to $txn ...
$db->connection()->commit($txn);
} catch (\Throwable $error) {
$db->connection()->cancel($txn);
throw $error;
} Explicit handles require the transactions feature, which depends on the WebSocket engine and a compatible server version. For most applications, a transaction block run with run() is simpler and works everywhere.
Learn more
Surreal API reference for the transaction methods
Executing queries for running statements