Builder::insert( $data )
Add operation to insert new records inside of the table that is used from the current model. A single entry can be set here as an array of key => value pairs, where the key is the column being saved and the value is the value intended to be saved.
Contents
A bulk insert is also supported, only rows of the same size can be inserted, an array of arrays representing each the column to be inserted, all rows should be the same length of columns and values as the rest of the rows inside of the data, otherwise the operation is won’t complete.
Parameters
-
(<span class="TECEventsCustom_TablesV1ModelsarrayTECEventsCustom_TablesV1Modelsarray<string,) (Required) mixed>|array<array<string,mixed> $data The data that is being inserted.
Return
(int) The number of affected rows.
Source
File: src/Events/Custom_Tables/V1/Models/Builder.php
public function insert( array $data ) {
// No data or operation was inserted.
if ( empty( $data ) ) {
return 0;
}
// If the first element is not an array make sure to wrap it around an array.
if ( ! is_array( reset( $data ) ) ) {
$data = [ $data ];
}
// @todo make this filterable?
$insert_batch_size = $this->batch_size;
$result = 0;
global $wpdb;
$wpdb->suppress_errors( true );
do {
$this_batch_data = array_splice( $data, 0, $insert_batch_size );
$validated = $this->validate_rows( $this_batch_data );
if ( empty( $validated['columns'] ) || empty( $validated['placeholders'] ) || empty( $validated['values'] ) ) {
return 0;
}
$columns = $validated['columns'];
$placeholders = $validated['placeholders'];
$SQL = "INSERT INTO {$wpdb->prefix}{$this->model->table_name()} ($columns) VALUES $placeholders";
$SQL = $wpdb->prepare( $SQL, ...$validated['values'] );
$this->queries[] = $SQL;
if ( $this->execute_queries ) {
$query_result = $wpdb->query( $SQL );
$result += (int) $query_result;
}
// Log our errors.
if ( $query_result === false && $wpdb->last_error ) {
do_action( 'tribe_log',
'error',
"ORM Builder mysql error while performing insert on {$this->model->table_name()}.", [
'source' => __METHOD__ . ':' . __LINE__,
'mysql error' => $wpdb->last_error,
] );
}
} while ( count( $data ) );
$wpdb->suppress_errors( false );
return $result;
}
Changelog
| Version | Description |
|---|---|
| 6.0.0 | Introduced. |