createManyAndReturn
Documentation for the createManyAndReturn
method, which inserts multiple records in bulk and returns the newly created records using optional filters and field inclusion.
Purpose
The createManyAndReturn
method is designed to insert multiple records into the database and return the newly created entries. It allows selecting specific fields, including related models, and optionally skipping duplicate records.
Parameters
'data'
- A non-empty list of associative arrays, each representing a row to insert (required).'skipDuplicates'
- Boolean flag to ignore duplicate entries when inserting (optional).'select'
- An array specifying which fields to return in the result set (optional).'include'
- An array specifying related models to include in the returned data (optional).'omit'
- An array of field names to exclude from the result (optional).
Return Value
Returns an array of created model objects that match the inserted rows. The result is filtered using select
, include
, or omit
if provided. If no rows were inserted, an empty array is returned.
Exception Handling
- Throws
InvalidArgumentException
if the'data'
key is missing or not a non-empty list. - Throws
InvalidArgumentException
if any row is not an associative array. - Throws
LogicException
if nested relation actions are attempted. - Throws
LogicException
if both'select'
and'include'
are provided. - Throws
Exception
if required fields are missing or enum validation fails. - Wraps entire operation in a database transaction and rolls back if any error occurs.
Features
- Efficiently inserts multiple rows in a single operation.
- Returns the full list of inserted records using filters.
- Handles default values, updated timestamps, and enum validation.
- Supports field omission via
omit
and precise field selection viaselect
. - Skips duplicates when supported by the underlying database.
- Works with PostgreSQL, SQLite, and MySQL with platform-specific handling.
Example Usage
use Lib\Prisma\Classes\Prisma;
$prisma = Prisma::getInstance();
$users = $prisma->user->createManyAndReturn([
'data' => [
[
'name' => 'Alice',
'email' => 'alice@example.com'
],
[
'name' => 'Bob',
'email' => 'bob@example.com'
]
],
'select' => [
'id' => true,
'name' => true
],
'skipDuplicates' => true
]);
echo "<pre>"; print_r($users); echo "</pre>";
Behavior When No Records Inserted
If no records are inserted due to constraints or skipDuplicates
being true
, the method returns an empty array:
$users = $prisma->user->createManyAndReturn([
'data' => [],
]);
// Result: []
print_r($users);