Builder::upsert_set( TECEventsCustom_TablesV1Modelsarray|TECEventsCustom_TablesV1Modelsarray<array> $models = array() )
Bulk updates instances of the Model.
Contents
Since MySQL does not come with a bulk update feature, this code will actually delete the existing model entries and re-insert them, by primary key, using the updated data.
Parameters
- $models
-
(<span class="TECEventsCustom_TablesV1Modelsarray">TECEventsCustom_TablesV1Modelsarray|<span class="TECEventsCustom_TablesV1Modelsarray<array>">TECEventsCustom_TablesV1Modelsarray<array>) (Optional) Either a list of Model instances to update, or a set of models in array format.
Default value: array()
Return
(int) The number of updated rows.
Source
File: src/Events/Custom_Tables/V1/Models/Builder.php
public function upsert_set( array $models = [] ) {
if ( ! count( $models ) ) {
return 0;
}
global $wpdb;
$table = $wpdb->prefix . $this->model->table_name();
$primary_key = $this->model->primary_key_name();
$expected_count = count( $models );
$keys = wp_list_pluck( $models, $primary_key );
$deleted = 0;
do {
$batch = array_splice( $keys, 0, $this->batch_size );
$keys_interval = implode( ',', array_map( 'absint', $batch ) );
$deleted += $wpdb->query( "DELETE FROM {$table} WHERE {$primary_key} IN ({$keys_interval})" );
} while ( count( $keys ) );
if ( $deleted !== $expected_count ) {
// There might be legit reasons, like another process running on the same table, but let's log it.
do_action( 'tribe_log', 'warning', 'Mismatching number of deletions.', [
'source' => __CLASS__,
'slug' => 'delete-in-upsert-set',
'table' => $table,
'primary_key' => $primary_key,
'expected' => $expected_count,
'deleted' => $inserted,
] );
}
$updates = $models;
// Here we make the assumptions the models will not be mixed bag, but either all arrays or all Models.
if ( ! is_array( reset( $models ) ) ) {
$updates = array_map( static function ( Model $model ) {
return $model->to_array();
}, $models );
}
$inserted = $this->insert( $updates );
if ( $inserted !== $expected_count ) {
// There might be legit reasons, like another process running on the same table, but let's log it.
do_action( 'tribe_log', 'warning', 'Mismatching number of insertions.', [
'source' => __CLASS__,
'slug' => 'delete-in-upsert-set',
'table' => $table,
'primary_key' => $primary_key,
'expected' => $expected_count,
'inserted' => $inserted,
] );
}
return $inserted;
}
Changelog
| Version | Description |
|---|---|
| 6.1.3 | Integration with memoization. |
| 6.0.0 | Introduced. |