Transaction

Execute multiple database operations as a single atomic unit. If any operation fails, the entire transaction is rolled back, ensuring full data integrity.

Purpose

The transaction method allows running a sequence of operations inside a single database transaction. If every operation succeeds, the transaction commits; if any fails, all changes are reverted. This ensures that complex workflows either fully succeed or fail without leaving the database in an inconsistent state.

Parameters

  • callable[] $operations — An array of anonymous functions, each representing one database action to execute within the transaction. They run sequentially.

Return Value

The method does not return a value. If all operations complete successfully, the transaction commits. If an error occurs, no changes are applied.

Error Handling

If any operation throws an exception, the transaction is immediately rolled back. The exception is rethrown, allowing the calling code to handle or log the error.

Example Usage

use Lib\Prisma\Classes\Prisma;

$prisma = Prisma::getInstance();

$operations = [
    function() use ($prisma) 
        $prisma->user->create([
            'data' => [
                'name' => 'John Doe'
            ]
        ]);
    ,
    function() use ($prisma) 
        $prisma->order->create([
            'data' => [
                'userId' => 1,
                'product' => 'Book'
            ]
        ]);
    
];

try 
    $prisma->transaction($operations);
    echo "Transaction successful.";
catch (\Exception $e) 
    echo "Transaction failed: " . $e->getMessage();