Builder::update( array|null $data = null )

Perform updates against a model that already exists on the database.


Parameters

$data

(array|null) (Optional) If the data is null the data of the model would be used to set an update, otherwise an array of column => value are used to construct the series of updates to perform against this model.

Default value: null


Top ↑

Return

(bool|int) False if the operation was unsuccessfully


Top ↑

Source

File: src/Events/Custom_Tables/V1/Models/Builder.php

	public function update( array $data = null ) {
		// Invalid on a where clause or previous value.
		if ( $this->invalid ) {
			return false;
		}

		if ( $data === null ) {
			$model = $this->set_data_to_model();
			$model->validate();
		} else {
			if ( empty( $data ) ) {
				return false;
			}

			$model = $this->set_data_to_model( $data );
			$model->validate( array_keys( $data ) );
		}

		if ( $model->is_invalid() ) {
			$this->invalid = true;

			return false;
		}

		list( $formatted_data, $format ) = $model->format();

		if ( empty( $formatted_data ) ) {
			return false;
		}

		$columns             = [];
		$replacements_values = [];
		foreach ( $formatted_data as $column => $value ) {
			if ( array_key_exists( $column, $format ) ) {
				$columns[]             = "`{$column}` = {$format[$column]}";
				$replacements_values[] = $value;
				continue;
			}

			if ( $value === null ) {
				$columns[] = "`{$column}` = NULL";
			}
		}

		global $wpdb;

		$this->operation = "UPDATE {$wpdb->prefix}{$this->model->table_name()}";

		$pieces = [
			$this->operation,
			"SET " . $wpdb->prepare( implode( ', ', $columns ), $replacements_values ),
		];

		$where = $this->get_where_clause();

		if ( $where !== '' ) {
			$pieces[] = $where;
		}

		$SQL = implode( "\n", $pieces );

		$this->queries[] = $SQL;

		return $this->execute_queries ? $wpdb->query( $SQL ) : false;
	}

Top ↑

Changelog

Changelog
Version Description
6.1.3 Integration with memoization.
6.0.0 Introduced.