Method Documentation: findUnique
Purpose
The findUnique
method is designed to retrieve either zero or one User record that matches the specified filter criteria from the database. It supports filtering based on conditions, selecting specific fields, and including related models in the result. This functionality ensures that the method is ideal for scenarios where a unique record is expected, such as fetching a user's profile.
Parameters
array $where
- An associative array specifying the filter criteria. It can contain keys for 'where', 'select', and 'include':- 'where' specifies the filter conditions to find the User.
- 'select' specifies the fields to be returned in the result.
- 'include' specifies related models to include in the result.
bool $format = false
- Optional. Specifies the format of the returned data ('false' or 'true') by default is array, but can also be set to 'true' for object format.
Return Value
Returns an associative array or an object containing the User data if a matching record is found, or an empty array if no User matches the filter criteria.
Exception Handling
Throws an \Exception
in the following scenarios:
- If both 'include' and 'select' options are used simultaneously, as they are mutually exclusive.
- If no valid 'where' filter is provided, to ensure that a query always executes with specific conditions.
- If any underlying database errors occur during the execution of the query.
Example Usage
use Lib\Prisma\Classes\Prisma;
$prisma = Prisma::getInstance();
$user = $prisma->user->findUnique([
'where' => ['id' => 'someUserId'],
]);
echo "<pre>";
echo "User found: " . print_r($user, true);
echo "</pre>";
Example Usage with include
This example demonstrates how to use the findUnique
method with the include
parameter to fetch a User record along with its related models.
use Lib\Prisma\Classes\Prisma;
$prisma = Prisma::getInstance();
$user = $prisma->user->findUnique([
'where' => ['id' => 'someUserId'],
'include' => [
'posts' => true,
'profile' => true
]
]);
echo "<pre>";
echo "User found: " . print_r($user, true);
echo "</pre>";
Example Usage with select
This example demonstrates how to use the findUnique
method with the select
parameter to fetch specific fields of a User record.
use Lib\Prisma\Classes\Prisma;
$prisma = Prisma::getInstance();
$user = $prisma->user->findUnique([
'where' => ['id' => 'someUserId'],
'select' => [
'name' => true,
'email' => true,
'role' => true,
'profile' => [
'select' => [
'id' => true,
'bio' => true
]
],
'posts' => [
'select' => [
'id' => true,
'title' => true
]
]
]
]);
echo "<pre>";
echo "User found: " . print_r($user, true);
echo "</pre>";