Yoast\WP\Lib

ORM::insert_many()publicYoast 1.0

Inserts multiple rows in a single query. Expects new rows as it's a strictly insert function, not an update one.

Метод класса: ORM{}

Хуки из метода

Возвращает

true|false. True for successful insert, false for failed.

Использование

$ORM = new ORM();
$ORM->insert_many( $models );
$models(массив) (обязательный)
Array of model instances to be inserted.

Код ORM::insert_many() Yoast 24.0

public function insert_many( $models ) {
	// Validate the input first.
	if ( ! \is_array( $models ) ) {
		throw new InvalidArgumentException( 'Invalid instances to be inserted' );
	}

	if ( empty( $models ) ) {
		return true;
	}

	$success = true;

	/**
	 * Filter: 'wpseo_chunk_bulked_insert_queries' - Allow filtering the chunk size of each bulked INSERT query.
	 *
	 * @param int $chunk_size The chunk size of the bulked INSERT queries.
	 */
	$chunk = \apply_filters( 'wpseo_chunk_bulk_insert_queries', 100 );
	$chunk = ! \is_int( $chunk ) ? 100 : $chunk;
	$chunk = ( $chunk <= 0 ) ? 100 : $chunk;

	$chunked_models = \array_chunk( $models, $chunk );
	foreach ( $chunked_models as $models_chunk ) {
		$values = [];

		// First, we'll gather all the dirty fields throughout the models to be inserted.
		$dirty_column_names = $this->get_dirty_column_names( $models_chunk );

		// Now, we're creating all dirty fields throughout the models and
		// setting them to null if they don't exist in each model.
		foreach ( $models_chunk as $model ) {
			$model_values = [];

			foreach ( $dirty_column_names as $dirty_column ) {
				// Set the value to null if it hasn't been set already.
				if ( ! isset( $model->orm->dirty_fields[ $dirty_column ] ) ) {
					$model->orm->dirty_fields[ $dirty_column ] = null;
				}

				// Only register the value if it is not null.
				if ( ! \is_null( $model->orm->dirty_fields[ $dirty_column ] ) ) {
					$model_values[] = $model->orm->dirty_fields[ $dirty_column ];
				}
			}
			$values = \array_merge( $values, $model_values );
		}

		// We now have the same set of dirty columns in all our models and also gathered all values.
		$query   = $this->build_insert_many( $models_chunk, $dirty_column_names );
		$success = $success && (bool) self::execute( $query, $values );
	}

	return $success;
}