Attach all of the IDs that aren't in the current array.

@param  array  $records
@param  array  $current
@param  bool   $touch
@return array
423799
protected function attachNew(array $records, array $current, $touch = true)
	{
		$changes = ['attached' => [], 'updated' => []];

		foreach ($records as $id => $attributes) {
			// If the ID is not in the list of existing pivot IDs, we will insert a new pivot
			// record, otherwise, we will just update this existing record on this joining
			// table, so that the developers will easily update these records pain free.
			if (! in_array($id, $current)) {
				$this->attach($id, $attributes, $touch);

				$changes['attached'][] = is_numeric($id) ? (int) $id : (string) $id;
			}

			// Now we'll try to update an existing pivot record with the attributes that were
			// given to the method. If the model is actually updated we will add it to the
			// list of updated pivot records so we return them back out to the consumer.
			elseif (count($attributes) > 0 &&
				$this->updateExistingPivot($id, $attributes, $touch)) {
				$changes['updated'][] = is_numeric($id) ? (int) $id : (string) $id;
			}
		}

		return $changes;
	}
396197
protected function bulkSend(array $records): void
    {
        try {
            $params = [
                'body' => [],
            ];

            foreach ($records as $record) {
                $params['body'][] = [
                    'index' => [
                        '_index' => $record['_index'],
                        '_type'  => $record['_type'],
                    ],
                ];
                unset($record['_index'], $record['_type']);

                $params['body'][] = $record;
            }

            $responses = $this->client->bulk($params);

            if ($responses['errors'] === true) {
                throw new ElasticsearchRuntimeException('Elasticsearch returned error for one of the records');
            }
        } catch (Throwable $e) {
            if (! $this->options['ignore_error']) {
                throw new RuntimeException('Error sending messages to Elasticsearch', 0, $e);
            }
        }
    }
1148437
public function detach($ids = null, $touch = true)
    {
        $query = $this->newPivotQuery();

        // If associated IDs were passed to the method we will only delete those
        // associations, otherwise all of the association ties will be broken.
        // We'll return the numbers of affected rows when we do the deletes.
        if (! is_null($ids = $this->parseIds($ids))) {
            if (count((array) $ids) === 0) {
                return 0;
            }

            $query->whereIn($this->relatedKey, (array) $ids);
        }

        // Once we have all of the conditions set on the statement, we are ready
        // to run the delete on the pivot table. Then, if the touch parameter
        // is true, we will go ahead and touch all related models to sync.
        foreach ($query->cursor() as $result) {
            $result->delete();
        }

        if ($touch) {
            $this->touchIfTouching();
        }

        return 1;
    }
453543
public function multiUpdate($records)
    {
        $ids = [];

        foreach ($records as $record) {
            try {
                $updatedRecord = $this->update($record);
                $ids[] = $updatedRecord[$this->getIdentifier()];
            } catch (\Throwable $e) {
                // TODO: need to log record that was not updated
                continue;
            }
        }

        return $ids;
    }
1055366
public function handleBatch(array $records)
    {
        $records = $this->recordFilter($records);
        if (empty($records)) {
            return true;
        }

        $lines = array_column($records, 'formatted');

        $this->write($lines);
    }
1162385
public function toRecords(string $recordClass): array
    {
        $array = [];
        foreach ($this->rows as $row) {
            /**
             * @var $row Row
             */
            $record = Record::instanceRecord($recordClass, $row->toArray());
            $record->setLoaded();
            $array[] = $record;
        }
        return $array;
    }
1194219
protected function createMissingAssignRecords(Collection $records, Collection $existing)
    {
        $existing = $existing->keyBy(function ($record) {
            return $this->getAttachRecordHash((array) $record);
        });

        $records = $records->reject(function ($record) use ($existing) {
            return $existing->has($this->getAttachRecordHash($record));
        });

        $this->newPivotTableQuery()->insert($records->all());
    }
1110364
public function insertAll($records): int
    {
        if (!is_iterable($records)) {
            throw new TypeError(sprintf('%s() expects argument passed to be iterable, %s given', __METHOD__, gettype($records)));
        }

        $bytes = 0;
        foreach ($records as $record) {
            $bytes += $this->insertOne($record);
        }

        $this->flush_counter = 0;
        $this->document->fflush();

        return $bytes;
    }
573634
public function updateExistingPivot($id, array $attributes, $touch = true)
	{
		if (in_array($this->updatedAt(), $this->pivotColumns)) {
			$attributes = $this->setTimestampsOnAttach($attributes, true);
		}

		$updated = $this->newPivotStatementForId($id)->update($attributes);

		if ($touch) {
			$this->touchIfTouching();
		}

		return $updated;
	}
679171
public function toggle($ids, $touch = true)
    {
        $changes = [
            'attached' => [], 'detached' => [],
        ];

        $records = $this->formatRecordsList((array) $this->parseIds($ids));

        // Next, we will determine which IDs should get removed from the join table by
        // checking which of the given ID/records is in the list of current records
        // and removing all of those rows from this "intermediate" joining table.
        $detach = array_values(array_intersect(
            $this->newPivotQuery()->pluck($this->relatedKey)->all(),
            array_keys($records)
        ));

        if (count($detach) > 0) {
            $this->detach($detach, false);

            $changes['detached'] = $this->castKeys($detach);
        }

        // Finally, for all of the records which were not "detached", we'll attach the
        // records into the intermediate table. Then, we will add those attaches to
        // this change list and get ready to return these results to the callers.
        $attach = array_diff_key($records, array_flip($detach));

        if (count($attach) > 0) {
            $this->attach($attach, [], false);

            $changes['attached'] = array_keys($attach);
        }

        // Once we have finished attaching or detaching the records, we will see if we
        // have done any attaching or detaching, and if we have we will touch these
        // relationships if they are configured to touch on any database updates.
        if ($touch && (count($changes['attached']) ||
            count($changes['detached']))) {
            $this->touchIfTouching();
        }

        return $changes;
    }
1043828
public function execute(array $records) : array {
        return array_map(function($record) {
            $contextid = $record->ctxid;
            context_helper::preload_from_record($record);
            $context = context::instance_by_id($contextid);
            return $context;
        }, $records);
    }
1087129
protected function mergeRecords(array $records)
    {
        foreach ($records as $key => $record) {
            if (null === $id = array_get($record, static::ID_FIELD)) {
                throw new InternalServerErrorException('No ' .
                    static::ID_FIELD .
                    ' field found in supplied record(s). Cannot merge record(s) for PATCH operation.');
            }

            $rs = $this->getConnection()->getDocument($this->transactionTable, $id);
            $record = array_merge($rs, $record);
            $records[$key] = $record;
        }

        return $records;
    }
315616
public function saveRecords(array $records, DataDimensions $dataDimensions = null)
    {

        if (!$dataDimensions) {
            $dataDimensions = $this->getCurrentDataDimensions();
        }

        $recordIds = [];
        foreach ($records as $record) {
            $recordIds[] = $this->saveRecord($record, $dataDimensions);
        }

        return $recordIds;

    }
425018
protected function createAttachRecords($ids, array $attributes)
	{
		$records = array();

		$timed = ($this->hasPivotColumn($this->createdAt()) ||
			      $this->hasPivotColumn($this->updatedAt()));

		// To create the attachment records, we will simply spin through the IDs given
		// and create a new record to insert for each ID. Each ID may actually be a
		// key in the array, with extra attributes to be placed in other columns.
		foreach ($ids as $key => $value)
		{
			$records[] = $this->attacher($key, $value, $attributes, $timed);
		}

		return $records;
	}
323851
private function formatRecord(array $records, $currentRecordIndex)
    {
        $record = $records[$currentRecordIndex];
        $recordAsString = '';

        if ($this->isLogInfoDisplayed($record)) {
            $logInfo = $this->formatLogInfo($record);
            $recordAsString .= $this->formatAsSection($logInfo);
        }

        if (isset($record['message']) && !empty($record['message'])) {
            $recordAsString .= $this->formatMessage($record).PHP_EOL;
        }

        if (isset($record['context']) && !empty($record['context'])) {
            // if the context contains an error stack trace, remove it to display it separately
            $stack = null;
            if (isset($record['context']['stack'])) {
                $stack = $record['context']['stack'];
                unset($record['context']['stack']);
            }

            $recordAsString .= $this->formatContext($record).PHP_EOL;

            if (null !== $stack) {
                $recordAsString .= '--> Stack Trace:'.PHP_EOL;
                $recordAsString .= $this->formatStackTrace($stack, '    | ');
            }
        }

        if (isset($record['extra']) && !empty($record['extra'])) {
            // don't display the extra information when it's identical to the previous log record
            $previousRecordExtra = isset($records[$currentRecordIndex - 1]) ? $records[$currentRecordIndex - 1]['extra'] : null;
            if ($record['extra'] !== $previousRecordExtra) {
                $recordAsString .= $this->formatExtra($record).PHP_EOL;
            }
        }

        return $recordAsString;
    }
62842
public function addContacts($contacts)
    {
        if (!is_array($contacts)) {
            return false;
        }
        foreach ($contacts as $contact) {
            if (!($contact  instanceof contact)) {
                return false;
            }
        }
        $this->contacts = array_merge($this->contacts, $contacts);

        return true;
    }
91662
protected function formatRecordsList(array $records)
    {

        $result = [];
        foreach ($records as $id => $attributes) {
             if (! is_array($attributes)) {
                list($id, $attributes) = [$attributes, []];
            }
            $result[$id] = $attributes;
        }
        return $result;
    }