PHP Method Documentation: CreateMany

This document offers a comprehensive overview of the createMany method, specifically designed for bulk insertion of new records into the database. It provides a way to efficiently create multiple records in a single operation, leveraging transactions to ensure data integrity. This method also allows for dynamic data validation, the handling of related records, and a mechanism to avoid duplicate entries, ensuring a robust solution for bulk data operations.

Purpose

The 'createMany' method is tailored for bulk insertion of records into the 'Users' table. It is particularly useful when multiple new user records need to be created simultaneously. By wrapping the operation in a database transaction, it ensures that all inserts are successfully completed or none at all, maintaining the integrity of the data. Additionally, with the option to skip duplicates, it offers flexibility in managing unique records, making the process more efficient and reliable.

Parameters

  • array $data - An associative array containing a 'data' key. The 'data' key should map to an array of associative arrays, each representing the data for a new User record to be created.
  • bool $skipDuplicates (optional) - A boolean flag that, when set to true, instructs the method to skip the insertion of records that would result in duplicate entries based on unique constraints in the database. This ensures that only unique records are added, preventing errors and maintaining data integrity.

Return Value

The method returns an array of the newly created User records, or an associative array containing details of the operation, including the number of records successfully inserted. If `skipDuplicates` is enabled, records that would cause duplication are not inserted, and the return value reflects the actual number of records added to the database.

Exception Handling

An exception is thrown if the 'data' key is not provided, if the input data is empty, or if an error occurs during any part of the database operation, including violation of unique constraints if `skipDuplicates` is not enabled. The method ensures that transactions are rolled back in the event of an error, preserving the consistency of the database.

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>";