80 lines
2 KiB
PHP
80 lines
2 KiB
PHP
<?php
|
|
|
|
namespace Nest\Database\Query;
|
|
|
|
use Nest\Database\Database;
|
|
use Nest\Database\Query\Where\HasWhere;
|
|
use Nest\Database\Exceptions\Query\MissingConditionValueException;
|
|
|
|
/**
|
|
* Builder of an UPDATE query.
|
|
*/
|
|
class UpdateQuery
|
|
{
|
|
use HasWhere;
|
|
|
|
/**
|
|
* Set values.
|
|
* @var array<string, Raw|string|int|float|null>
|
|
*/
|
|
protected array $set = [];
|
|
|
|
/**
|
|
* Create a new UPDATE query.
|
|
* @param Database $database The database on which to execute the query.
|
|
* @param string $table Base table of the UPDATE query.
|
|
*/
|
|
public function __construct(protected Database $database, protected string $table)
|
|
{}
|
|
|
|
/**
|
|
* Get the database on which to execute the query.
|
|
* @return Database
|
|
*/
|
|
public function getDatabase(): Database
|
|
{
|
|
return $this->database;
|
|
}
|
|
|
|
/**
|
|
* Reset set values.
|
|
* @return $this
|
|
*/
|
|
public function resetSet(): static
|
|
{
|
|
$this->set = [];
|
|
return $this;
|
|
}
|
|
|
|
/**
|
|
* Add set columns values.
|
|
* @param string|array<string, Raw|string|int|float|null> $column The name of the column in column mode, or an associative array of all set columns with their corresponding value.
|
|
* @param Raw|string|int|float|null $value The value to set, when setting in column mode (with a column as first parameter).
|
|
* @return $this
|
|
*/
|
|
public function set(string|array $column, Raw|string|int|float|null $value = null): static
|
|
{
|
|
if (is_array($column))
|
|
{ // The first parameter is an array, adding set values in array mode.
|
|
$this->set = array_merge($this->set, $column);
|
|
}
|
|
else
|
|
{ // The first parameter is a string, adding set value in column mode.
|
|
$this->set[$column] = $value;
|
|
}
|
|
|
|
return $this;
|
|
}
|
|
|
|
/**
|
|
* Execute update query.
|
|
* @param bool $returning True to return inserted objects.
|
|
* @return object[]|bool Updated objects if returning is true, true otherwise.
|
|
* @throws MissingConditionValueException
|
|
*/
|
|
public function execute(bool $returning = false): array|bool
|
|
{
|
|
// Execute built query and return result.
|
|
return $this->database->getQueriesAdapter()->update($this->table, $this->set, $this->wheres, $returning);
|
|
}
|
|
}
|