Get the records to bulk insert.

@param  array[] $insertedPKs
@return array
763956
public function getInsertRecords(array $insertedPKs)
    {
        $this->run($insertedPKs, false);

        $tables = [];
        $pivotRecords = [];
        $foreignKeys = [];

        foreach ($this->pivotPopulators as $relatedClass => $pivotPopulator) {
            if (!isset($insertedPKs[$relatedClass])) {
                continue;
            }

            list($table, $pivotRecordsOfOneRelation, $foreignKey) = $pivotPopulator->getInsertRecords(
                $this->model,
                $insertedPKs
            );

            // A model's inverse MorphToMany relations use the same pivot table,
            // so we have to use the related class as index to differentiate them.
            $tables[$relatedClass] = $table;
            $pivotRecords[$relatedClass] = $pivotRecordsOfOneRelation;
            $foreignKeys[$relatedClass] = $foreignKey;
        }

        return [$this->model, $tables, $pivotRecords, $foreignKeys];
    }
607977
public function insertMany(array $sets)
    {
        if (count($sets)) {
            if (method_exists($this, 'insertRecordSets')) {
                foreach ($sets as $set) {
                    $this->insertRecordSets($set);
                    if ($this->recordOrdering === true && empty($sets[ 'record_ordering' ])) {
                        $set[ 'record_ordering' ] = $this->getRecordOrdering($this->table);
                    }
                }
            }

            if (method_exists($this, 'beforeInsertMany')) {
                $this->beforeInsertMany($sets);
            }

            if ($this->qb->table($this->table)->insertBatch($sets)) {
                if (method_exists($this, 'afterInsertMany')) {
                    return $this->afterInsertMany();
                }

                return $this->db->getAffectedRows();
            }
        }

        return false;
    }
1156319
public function batchInsert($rows)
    {
        $insertedIds = $this->db->batchInsert($this->name, $rows);

        foreach ($rows as $key => $row) {
            $rows[$key]['_id'] = $insertedIds[$key];
        }

        return $rows;
    }
319118
public static function bulkDelete(array $records, array $params = [])
    {
        if (empty($records)) {
            throw new BadRequestException('There is no record in the request.');
        }

        $response = [];
        $errors = false;
        $rollback = array_get_bool($params, ApiOptions::ROLLBACK);
        $continue = array_get_bool($params, ApiOptions::CONTINUES);

        if ($rollback) {
            //	Start a transaction
            DB::beginTransaction();
        }

        foreach ($records as $key => $record) {
            try {
                $m = new static;
                $pk = $m->getPrimaryKey();
                $id = array_get($record, $pk);
                $response[$key] = static::deleteInternal($id, $record, $params);
            } catch (\Exception $ex) {
                // track the index of the error and copy error to results
                $errors = true;
                $response[$key] = $ex;
                if ($rollback || !$continue) {
                    break;
                }
            }
        }

        if ($errors) {
            $msg = "Batch Error: Not all requested records could be deleted.";
            if ($rollback) {
                DB::rollBack();
                $msg .= " All changes rolled back.";
            }

            throw new BatchException($response, $msg);
        }

        if ($rollback) {
            DB::commit();
        }

        return $response;
    }
525326
public function getOtherRequiredPrimaryKeys(array $primaryKeys)
    {
        $pks = [];
        foreach ($this->getPrimaryKey() as $primaryKey) {
            if ($primaryKey->isNotNull() && !$primaryKey->hasDefaultValue() && !in_array($primaryKey, $primaryKeys, true)) {
                $pks = $primaryKey;
            }
        }

        return $pks;
    }
1172590
private function _insert($table_name, $keyed_array)
	{
		// Get the schema and primary key
		$table_schema      = self::_getTableSchema($table_name);
		$table_primary_key = self::_getTablePrimaryKey($table_name);

		// Get the columns and values
		list($parameter_columns, $parameter_values) = Validation::validateTableInput($table_name, $table_schema, $table_primary_key, $keyed_array);

		// Escape the column names
		$parameter_columns = self::_escapeColumnNames($parameter_columns);

		// List the number of parameters - Function creates an array of range 1..n and prepends '$' to each number
		$parameter_placeholders = self::_calculateInputPlaceholders($parameter_columns);

		// Clean the table name
		$table_name = self::_getCleanTableName($table_name);

		// Construct the INSERT statement
		$sql = '
			INSERT INTO ' . $table_name . ' (' . implode(', ', $parameter_columns) . ')
			VALUES (' . implode(', ', $parameter_placeholders) . ')
			RETURNING *;
		';

		// Sanitize and run the query
		$rows = Utility::pgQueryParams($sql, $parameter_values);

		// Validate result, check that primary key is set
		if (empty($rows) || !array_key_exists('0', $rows) || !array_key_exists($table_primary_key, $rows[0]))
		{
			Utility::throwException('Record not found for ' . $table_name . ' with a primary key value of ' . $primary_key_value);
		}

		// Return the only record
		return $rows[0];
	}
677682
protected function pickMorphOwner(array $insertedPKs, $alwaysAssociate)
    {
        $owners = $this->populator->getMorphToClasses(get_class($this->model));

        // We'll share the chosen owner between the foreign key and morph type closures
        // by saving it in $this until the next call to this method.
        if ($this->morphOwner === false) {
            if (!$alwaysAssociate && rand(0, 1)) {
                return $this->morphOwner = null;
            }

            // Filters the owning classes that have been added to Populator.
            $owners = array_filter($owners, function ($owner) use ($insertedPKs) {
                return isset($insertedPKs[$owner]);
            });

            return $this->morphOwner = $this->generator->randomElement($owners);
        }

        return tap($this->morphOwner, function () {
            // We'll unset the picked owner,
            // so it will be picked again randomly when the next model is created.
            $this->morphOwner = false;
        });
    }
1030003
private static function populateIds(&$insertModels, $pks, $lastPk, $insertedCount)
    {
        while($insertedCount > 0 && $insertedCount <= count($insertModels))
        {
            $insertedCount--;
            $model = $insertModels[$insertedCount];
            $model->{$pks[0]} = $lastPk;
            $lastPk = intval($lastPk) - 1;
        }
    }
735179
private function getSingleResult($pk)
    {
        $model = $this->_get($pk);
        $code = 200;
        $return = array();
        if (NULL === $model || !method_exists($model, 'toArray')) {
            $code = 404;
        } else {
            $return = $model->toArray($this->fieldType ?: TableMap::TYPE_PHPNAME, true, [], true);
        }

        return array($code, $return);
    }
669185
function getPrimaryKeyValues() {
		$arr = array();
		$pks = static::$_primaryKeys;

		foreach ($pks as &$pk) {
			$arr[] = $this->{"get$pk"}();
		}

		return $arr;
	}
273981
private function getInsertQuery()
    {
        return 'INSERT INTO '.$this->parts['from'][0]['table'].
               ' ('.implode(', ', array_keys($this->parts['set'])).')'.
               ' VALUES'.
               ' ('.implode(', ', $this->parts['set']).')';
    }
888042
public function bulkUploadFiles(array $requests): array
    {
        $body = [];
        foreach ($requests as $request) {
            $body[] = [
                'contentType' => $request->getContentType(),
                'expires' => $request->getExpires(),
                'access' => $request->getAccess(),
            ];
        }

        $decodedBulkResponse = json_decode($this->request('file.requestUpload', $body)->getBody()->getContents(), true);
        $uploadInstructions = [];
        /** @var string[][] $instructionData */
        foreach ($decodedBulkResponse as $instructionData) {
            $uploadInstructions[] = UploadInstructionFactory::createFromArray($instructionData);
        }

        return $uploadInstructions;
    }
992804
public function filterInsertValues($data, $fields)
	{
		$insertValues = array();
		$field_keys = array_flip($fields);
		foreach ($data as $key => $values) {
			$filteredValues = array_intersect_key($values, $field_keys);
			$emptyFields = array_fill_keys($fields, null);
			$filledValues = array_values(array_merge($emptyFields, $filteredValues));
			$insertValues = array_merge($insertValues, $filledValues);
		}
		return $insertValues;
	}
327549
protected function fillModel(Model $model, array $insertedPKs)
    {
        $attributes = $this->mergeAttributes($model);

        // To maximize the number of attributes already set in the
        // model when accessing it from closure custom attributes,
        // we'll first set all the non-closure attributes.
        $closureAttributes = [];

        foreach ($attributes as $key => $value) {
            // Don't use is_callable() here since it returns true for values
            // that happen to be function names, e.g. country code "IS".
            if ($value instanceof \Closure) {
                $closureAttributes[$key] = $value;
            } else {
                $model->$key = $value;
            }
        }

        // We'll set the remaining attributes as we evaluate the closures,
        // so that the model will have the return values of previous closures already set.
        foreach ($closureAttributes as $key => $value) {
            $model->$key = $value($model, $insertedPKs);
        }
    }
950192
public static function bulkCreate(array $records, array $params = [])
    {
        if (empty($records)) {
            throw new BadRequestException('There are no record sets in the request.');
        }

        $response = [];
        $errors = false;
        $rollback = array_get_bool($params, ApiOptions::ROLLBACK);
        $continue = array_get_bool($params, ApiOptions::CONTINUES);

        if ($rollback) {
            //	Start a transaction
            DB::beginTransaction();
        }

        foreach ($records as $key => $record) {
            try {
                $response[$key] = static::createInternal($record, $params);
            } catch (\Exception $ex) {
                $errors = true;
                $response[$key] = $ex;
                // track the index of the error and copy error to results
                if ($rollback || !$continue) {
                    break;
                }
            }
        }

        if ($errors) {
            $msg = "Batch Error: Not all requested records could be created.";
            if ($rollback) {
                DB::rollBack();
                $msg .= " All changes rolled back.";
            }

            throw new BatchException($response, $msg);
        }

        if ($rollback) {
            DB::commit();
        }

        return $response;
    }
1234415
public function getRecipientsFromPost(array $referenced_entity) {
    $recipients = [];

    $post = Post::load($referenced_entity['target_id']);
    $recipient_user = $post->get('field_recipient_user')->getValue();
    if (!empty($recipient_user)) {
      $recipients[] = [
        'target_type' => 'user',
        'target_id' => $recipient_user['0']['target_id'],
      ];
    }

    return $recipients;
  }
927085
public int[] insert(Collection<Entity> records) throws SQLException {
		Connection conn = null;
		try {
			conn = this.getConnection();
			return runner.insert(conn, records);
		} catch (SQLException e) {
			throw e;
		} finally {
			this.closeConnection(conn);
		}
	}