createMany

The createMany method allows bulk insertion of multiple records in a single database operation, ensuring data integrity through transactions and offering optional duplicate skipping.

Purpose

The createMany method inserts multiple records at once into the database. It wraps all inserts inside a transaction, ensuring that either all records are created or none are. With skipDuplicates, you can prevent errors caused by unique constraint violations while efficiently importing large datasets.

Parameters

  • data – Required. An array of associative arrays, each representing a new record.
  • skipDuplicates – Optional boolean. When true, records violating unique constraints are ignored instead of causing an error.

Return Value

Returns an array containing the result of the bulk insertion, including the number of records successfully inserted. When skipDuplicates is enabled, duplicate entries are silently ignored.

Exception Handling

  • Throws exception if data is missing or empty.
  • Throws if a unique constraint is violated while skipDuplicates is false.
  • On failure, the transaction is rolled back to maintain integrity.

Example Usage

Creating Multiple New User Records

use Lib\Prisma\Classes\Prisma;

$prisma = Prisma::getInstance();
$createdUsers = $prisma->user->createMany([
    'data' => [
        [
            'name' => 'Alice',
            'email' => 'alice@example.com',
            'password' => 'securePassword123'
        ],
        [
            'name' => 'Bob',
            'email' => 'bob@example.com',
            'password' => 'anotherSecurePassword456'
        ]
    ],
    'skipDuplicates' => true
]);

echo "<pre>";
echo "Users created: " . print_r($createdUsers, true);
echo "</pre>";