Documentation · Chapter 13

Track changes and commit them safely.

DbContext remembers loaded entities, compares snapshots, and commits the complete unit of work atomically. Nested transactions use savepoints when the driver supports them.

Every lesson starts from the problem, explains the mechanism, then gives a concrete verification.

Snapshots reveal real changes

When an entity is loaded, the context stores a snapshot. Changing an ordinary property is enough; pendingChanges explains what will be inserted, updated, or removed.

phpaml — zsh
$user = $context->set(User::class)->find(42);
$user->name = 'Ada';

$context->transaction(function () use ($context): void {
    $context->saveChanges();
});

saveChanges is a unit of work

saveChanges wraps all pending mutations in one transaction. Either the complete business operation succeeds or none of it is committed, and a failed unit remains available for diagnosis or retry.

Transactions and savepoints protect consistency

transaction() defines an explicit boundary. A transaction opened inside another uses a savepoint where supported, allowing the inner operation to roll back without corrupting the outer one.