Method Documentation: upsert
Purpose
The upsert
method is designed to simplify database operations by merging the functionalities of insert and update actions into one. It performs an atomic operation that checks for the existence of a User record based on specified criteria. If the record exists, it updates the record with new data; otherwise, it creates a new User record. This method is essential for ensuring data consistency and integrity while reducing the need for separate insert and update operations.
Parameters
array $data
- Associative array containing keys for 'where', 'create', 'update', with optional 'select', and 'include' keys for more advanced operations.string $format
- Specifies the return format of the operation ('array' or 'object'), allowing for flexible result handling.
Return Value
Returns an array or object based on the specified $format
parameter. This return value includes either the primary key of the updated or newly created record, or a boolean true
to signify a successful update.
Error Handling
Throws an \Exception
if essential keys ('where', 'create', 'update') are missing from the $data
array, or if invalid criteria keys are provided. Additionally, transaction management ensures that any errors during the operation result in a rollback to maintain database integrity.
Example Usage
use Lib\Prisma\Classes\Prisma;
$prisma = Prisma::getInstance();
$result = $prisma->user->upsert([
'where' => ['email' => 'user@example.com'],
'create' => [
'name' => 'New User',
'email' => 'user@example.com',
'password' => 'newuserpassword'
],
'update' => ['name' => 'Updated User Name'],
'select' => [
'name' => true,
'email' => true
]
]);
echo "<pre>";
echo "Upserted user: " . print_r($result, true);
echo "</pre>";