findUniqueOrThrow

Documentation for the findUniqueOrThrow method, which retrieves a unique record from the database based on the provided criteria or throws an exception if no record is found.

Purpose

The findUniqueOrThrow method is designed to retrieve a single record that uniquely matches the provided criteria. If no match is found, it throws an exception. This ensures the record exists and prevents silent failures in critical workflows.

Parameters

  • 'where' - An associative array that uniquely identifies the record using a unique field or compound key.
  • 'select' - (Optional) Array of fields to return.
  • 'include' - (Optional) Array of related models to include.
  • 'omit' - (Optional) Array of field names to exclude from the result.

Return Value

Returns a single object representing the uniquely matched record. If no record is found, an exception is thrown. This guarantees that the result is never null.

Exception Handling

  • Throws an Exception if no record matches the unique filter criteria.
  • Throws an exception if both 'include' and 'select' are provided simultaneously.
  • Throws an exception if 'where' is missing or does not contain valid unique filters.
  • Throws an exception if any unsupported key is used in the criteria array.

Features

  • Guarantees exactly one record matched by unique fields.
  • Fails fast by throwing when no match is found.
  • Supports precise field selection and relation inclusion.
  • Allows field omission for cleaner results.

Example Usage

use Lib\Prisma\Classes\Prisma;

$prisma = Prisma::getInstance();

try {
    $user = $prisma->user->findUniqueOrThrow([
        'where' => [
            'id' => 1
        ],
        'select' => [
            'id' => true,
            'name' => true,
            'email' => true
        ]
    ]);

    echo "<pre>"; print_r($user); echo "</pre>";
} catch (Exception $e) {
    echo "Error: " . $e->getMessage();
}

Behavior When No Record Found

If the specified unique record is not found, the method throws an exception immediately. This behavior is useful when the presence of the record is required for the operation to continue.

try {
    $user = $prisma->user->findUniqueOrThrow([
        'where' => ['email' => 'missing@example.com']
    ]);
} catch (Exception $e) {
    echo "User not found.";
}