Upsert

The upsert method creates a new record or updates an existing one depending on whether the where condition matches an existing entry. It ensures that the record always exists after execution.

Purpose

The upsert method combines the logic of create and update in one action. If the specified record exists, it is updated. If not, a new one is created. This guarantees that the record always exists after calling the method.

Parameters

  • where — Required. Unique filter to find the existing record.
  • create — Required. Data to create the record if it does not exist.
  • update — Required. Data to update the record if it does exist.
  • select — Optional. Choose specific fields to return.
  • include — Optional. Include related models.
  • omit — Optional. Exclude specific fields from the result.

Return Value

Returns the created or updated record. The response is shaped using select, include, or omit if provided.

Exception Handling

  • Throws an Exception if where, create, or update is missing.
  • Throws a LogicException if both select and include are used together.
  • Throws an Exception for invalid keys or structure in the criteria.
  • All actions are executed inside a transaction; errors trigger a rollback.

Example Usage

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
    ]
]);