findUnique

Documentation for the findUnique method, which retrieves a unique record based on a primary or unique key.

Purpose

The findUnique method is designed to retrieve a single unique record from the database. This method strictly requires a valid unique identifier such as a primary key or other uniquely constrained field. It ensures precise data retrieval and returns null if no matching record is found.

Parameters

  • 'where' (required) - An associative array containing a primary key or unique field used to identify the record.
  • 'select' - An array specifying the fields to be returned in the result.
  • 'include' - An array specifying related models to include.
  • 'omit' - An array of field names to exclude from the result.

Return Value

Returns a single object representing the record that matches the unique condition provided. If no matching record exists, it returns null.

Exception Handling

  • Throws an exception if the 'where' key is missing or not an array.
  • Throws an exception if no valid unique field is found in the 'where' condition.
  • Throws an exception if both 'select' and 'include' are used simultaneously.
  • Throws an exception if unsupported keys are present in the input criteria.

Features

  • Designed for exact match queries using unique constraints.
  • Supports selective field retrieval and omission.
  • Supports inclusion of related models.
  • Validates query structure and conditions before execution.

Example Usage: By ID

use Lib\Prisma\Classes\Prisma;

$prisma = Prisma::getInstance();
$user = $prisma->user->findUnique([
    'where' => [
        'id' => 1
    ]
]);

echo "<pre>";
print_r($user);
echo "</pre>";

Example Usage: Unique by Email

$user = $prisma->user->findUnique([
    'where' => [
        'email' => 'john@example.com'
    ],
    'select' => [
        'id' => true,
        'name' => true,
        'email' => true
    ]
]);

Example Usage: Including Related Model

$user = $prisma->user->findUnique([
    'where' => [
        'id' => 1
    ],
    'include' => [
        'profile' => true
    ]
]);