upsert
Documentation for the upsert method, which creates a new record or updates an existing one based on unique criteria.
Purpose
The upsert
method is used to either create a new record or update an existing one based on whether a match is found with the given 'where'
condition. This method ensures that the record always exists after execution.
Parameters
'where'
(required) - An associative array defining the unique key condition to search for an existing record.'create'
(required) - An associative array of data to be used for creating a new record if none exists.'update'
(required) - An associative array of data to be used for updating the record if it exists.'select'
- An array specifying which fields to return.'include'
- An array specifying related models to return.'omit'
- An array of field names to exclude from the result.
Return Value
Returns an object representing the newly created or updated record. The fields included depend on the 'select'
, 'include'
, or 'omit'
criteria provided.
Exception Handling
- Throws an exception if any of the required keys (
'where'
,'create'
,'update'
) are missing. - Throws an exception if both
'select'
and'include'
are provided simultaneously. - Throws an exception if invalid keys are found in the criteria array.
- Automatically rolls back the transaction if an error occurs during execution.
Features
- Combines create and update logic into a single call.
- Ensures that a matching record always exists after execution.
- Supports field omission and selective inclusion of related models.
- Executes within a secure transaction to prevent partial updates.
Example Usage: Create if Not Found
use Lib\Prisma\Classes\Prisma;
$prisma = Prisma::getInstance();
$user = $prisma->user->upsert([
'where' => [
'email' => 'jane@example.com'
],
'create' => [
'name' => 'Jane Doe',
'email' => 'jane@example.com',
'isActive' => true
],
'update' => [
'isActive' => true
],
'select' => [
'id' => true,
'name' => true,
'email' => true
]
]);
echo "<pre>";
print_r($user);
echo "</pre>";
Example Usage: Include Related Model
$user = $prisma->user->upsert([
'where' => [
'email' => 'jane@example.com'
],
'create' => [
'name' => 'Jane Doe',
'email' => 'jane@example.com'
],
'update' => [
'name' => 'Jane Updated'
],
'include' => [
'profile' => true
]
]);