findFirst

Documentation for the findFirst method, which retrieves the first User record matching the given filter criteria.

Purpose

The findFirst method is designed to retrieve the first User record that matches the specified filter criteria. It supports conditional filtering, ordering, selective field inclusion, and related model inclusion. Unlike findMany, this method returns only a single result or null if no match is found.

Parameters

  • 'where' - An associative array specifying the filter conditions.
  • 'orderBy' - An associative array specifying how results should be sorted before selecting the first record.
  • 'cursor' - An associative array to define a starting point using cursor-based pagination.
  • 'select' - An array indicating which fields to return in the result.
  • 'include' - An array indicating related models to include in the result.
  • 'distinct' - Boolean flag to ensure distinct results.
  • 'omit' - An array of field names to exclude from the result.

Return Value

Returns a single object of the requested type if a matching record is found, or null if no match is found. For example, for the User model, it will return one User object or null.

Exception Handling

  • Throws an exception if 'include' and 'select' are used together.
  • Throws an exception if 'where' is not an array or is empty when provided.
  • Throws an exception if invalid keys are used in the criteria array.

Features

  • Returns the first matching record, optionally sorted by fields.
  • Supports filtering with nested relations and logical operators.
  • Allows precise field selection or omission.
  • Includes related models when required.
  • Supports cursor-based pagination for advanced queries.

Example Usage

use Lib\Prisma\Classes\Prisma;

$prisma = Prisma::getInstance();
$user = $prisma->user->findFirst([
    'where' => [
        'email' => [
            'equals' => 'john@example.com'
        ]
    ],
    'orderBy' => [
        'createdAt' => 'desc'
    ],
    'select' => [
        'id' => true,
        'name' => true,
        'email' => true
    ]
]);

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

Behavior When No Record Found

If no record matches the given conditions, findFirst returns null. This helps in safely checking for non-existent records:

if (!$user) {
    echo "User not found.";
} else {
    echo "User email: " . $user->email;
}