# Transactions

Batch Surqlize ORM queries into a single SurrealDB transaction with automatic rollback, and handle the validation exceptions Surqlize raises.

`ConnectionManager::transaction()` runs a set of ORM queries inside one transaction. It passes a transaction executor to your callback; run your queries through that executor with `withExecutor()` or the `executor:` argument. The transaction commits when the callback returns, and rolls back if it throws.

```php
use Surqlize\Connection\ConnectionManager;

ConnectionManager::transaction(function ($transaction): void {
    User::select(['name'])
        ->where(fn ($user) => $user->name->eq('beau'))
        ->withExecutor($transaction)
        ->collect();

    User::createQuery([
        'name' => 'tobie',
        'age' => 30,
    ], executor: $transaction)->execute();
});
```

If the callback throws, the transaction is rolled back and the exception is rethrown, so the batch either applies in full or not at all.

> [!NOTE]
> Every query inside the callback must use the transaction executor. A query that resolves the global executor instead runs outside the transaction.

## Validation and errors

Surqlize validates several contracts before it builds or executes a query, and raises typed exceptions when they fail.

- Model classes must extend `Surqlize\Model\Model`, and edge classes must extend `Surqlize\Edge\Edge`.
- Table and field identifiers are validated before compilation.
- `findOrFail()` throws `Surqlize\Model\Exception\ModelNotFoundException` when no record matches.
- Schema validation rules run before `create()` and `save()`, and a failing rule raises a `ValidationException`.
- Persistence methods throw when a required `RecordId` is missing.
- `RELATE` validates the edge endpoint classes and their record ids.

## Learn more

- [Connections](/docs/reference/php/libraries/surqlize/connections.md) for executor injection
- [Mutations](/docs/reference/php/libraries/surqlize/mutations.md) for the queries you batch
- [Transactions in the SDK](/docs/reference/php/v2/concepts/transactions.md) for the underlying mechanism
