Skip to content
PHP Ecosystem
Explore

Command

API reference › yii › db › Command

classyii\db\Command
Extendsyii\base\Component » yii\base\BaseObject
Implementsyii\base\Configurable
Since2.0
Sourceframework/db/Command.php
3 subclasses

Command represents a SQL statement to be executed against a database.

A command object is usually created by calling Connection::createCommand(). The SQL statement it represents can be set via the $sql property.

To execute a non-query SQL (such as INSERT, DELETE, UPDATE), call execute(). To execute a SQL statement that returns a result data set (such as SELECT), use queryAll(), queryOne(), queryColumn(), queryScalar(), or query().

For example,

$users = $connection->createCommand('SELECT * FROM user')->queryAll();

Command supports SQL statement preparation and parameter binding. Call bindValue() to bind a value to a SQL parameter; Call bindParam() to bind a PHP variable to a SQL parameter. When binding a parameter, the SQL statement is automatically prepared. You may also call prepare() explicitly to prepare a SQL statement.

Command also supports building SQL statements by providing methods such as insert(), update(), etc. For example, the following code will create and execute an INSERT SQL statement:

$connection->createCommand()->insert('user', [
'name' => 'Sam',
'age' => 30,
])->execute();

To build SELECT SQL statements, please use Query instead.

For more details and usage information on Command, see the guide article on Database Access Objects.

PropertyTypeDescriptionDefined by
$behaviors read-onlyarray<yii\base\Behavior<static>>List of behaviors attached to this component.yii\base\Component
$dbConnectionThe DB connection that this command is associated with Default: null.Command
$fetchModeintThe default fetch mode for this command. Default: \PDO::FETCH_ASSOC.Command
$paramsarrayThe parameters (name => value) that are bound to the current PDO statement. Default: [].Command
$pdoStatementPDOStatement|nullThe PDOStatement object that this command is associated with Default: null.Command
$queryCacheDependencyyii\caching\DependencyThe dependency to be associated with the cached query result for this command Default: null.Command
$queryCacheDurationintThe default number of seconds that query results can remain valid in cache. Default: null.Command
$rawSqlstringThe raw SQL with parameter values inserted into the corresponding placeholders in $sql.Command
$sqlstringThe SQL statement to be executed.Command
$pendingParams protectedarrayPending parameters to be bound to the current PDO statement. Default: []. Available since 2.0.33.Command
MethodDescriptionDefined by
__construct()Constructor.yii\base\BaseObject
__call()Calls the named method which is not a class method.yii\base\Component
__clone()This method is called after the object is created by cloning an existing one.yii\base\Component
__get()Returns the value of a component property.yii\base\Component
__isset()Checks if a property is set, i.e. defined and not null.yii\base\Component
__set()Sets the value of a component property.yii\base\Component
__unset()Sets a component property to be null.yii\base\Component
addCheck()Creates a SQL command for adding a check constraint to an existing table.Command
addColumn()Creates a SQL command for adding a new DB column.Command
addCommentOnColumn()Builds a SQL command for adding comment to column.Command
addCommentOnTable()Builds a SQL command for adding comment to table.Command
addDefaultValue()Creates a SQL command for adding a default value constraint to an existing table.Command
addForeignKey()Creates a SQL command for adding a foreign key constraint to an existing table.Command
addPrimaryKey()Creates a SQL command for adding a primary key constraint to an existing table.Command
addUnique()Creates a SQL command for adding an unique constraint to an existing table.Command
alterColumn()Creates a SQL command for changing the definition of a column.Command
attachBehavior()Attaches a behavior to this component.yii\base\Component
attachBehaviors()Attaches a list of behaviors to the component.yii\base\Component
batchInsert()Creates a batch INSERT command.Command
behaviors()Returns a list of behaviors that this component should behave as.yii\base\Component
bindParam()Binds a parameter to the SQL statement to be executed.Command
bindValue()Binds a value to a parameter.Command
bindValues()Binds a list of values to the corresponding parameters.Command
cache()Enables query cache for this command.Command
cancel()Cancels the execution of the SQL statement.Command
canGetProperty()Returns a value indicating whether a property can be read.yii\base\Component
canSetProperty()Returns a value indicating whether a property can be set.yii\base\Component
checkIntegrity()Builds a SQL command for enabling or disabling integrity check.Command
className() staticReturns the fully qualified name of this class.yii\base\BaseObject
createIndex()Creates a SQL command for creating a new index.Command
createTable()Creates a SQL command for creating a new DB table.Command
createView()Creates a SQL View.Command
delete()Creates a DELETE command.Command
detachBehavior()Detaches a behavior from the component.yii\base\Component
detachBehaviors()Detaches all behaviors from the component.yii\base\Component
dropCheck()Creates a SQL command for dropping a check constraint.Command
dropColumn()Creates a SQL command for dropping a DB column.Command
dropCommentFromColumn()Builds a SQL command for dropping comment from column.Command
dropCommentFromTable()Builds a SQL command for dropping comment from table.Command
dropDefaultValue()Creates a SQL command for dropping a default value constraint.Command
dropForeignKey()Creates a SQL command for dropping a foreign key constraint.Command
dropIndex()Creates a SQL command for dropping an index.Command
dropPrimaryKey()Creates a SQL command for removing a primary key constraint to an existing table.Command
dropTable()Creates a SQL command for dropping a DB table.Command
dropUnique()Creates a SQL command for dropping an unique constraint.Command
dropView()Drops a SQL View.Command
ensureBehaviors()Makes sure that the behaviors declared in behaviors() are attached to this component.yii\base\Component
execute()Executes the SQL statement.Command
executeResetSequence()Executes a db command resetting the sequence value of a table’s primary key.Command
getBehavior()Returns the named behavior object.yii\base\Component
getBehaviors()Returns all behaviors attached to this component.yii\base\Component
getRawSql()Returns the raw SQL by inserting parameter values into the corresponding placeholders in $sql.Command
getSql()Returns the SQL statement for this command.Command
hasEventHandlers()Returns a value indicating whether there is any handler attached to the named event.yii\base\Component
hasMethod()Returns a value indicating whether a method is defined.yii\base\Component
hasProperty()Returns a value indicating whether a property is defined for this component.yii\base\Component
init()Initializes the object.yii\base\BaseObject
insert()Creates an INSERT command.Command
noCache()Disables query cache for this command.Command
off()Detaches an existing event handler from this component.yii\base\Component
on()Attaches an event handler to an event.yii\base\Component
prepare()Prepares the SQL statement to be executed.Command
query()Executes the SQL statement and returns query result.Command
queryAll()Executes the SQL statement and returns ALL rows at once.Command
queryColumn()Executes the SQL statement and returns the first column of the result.Command
queryOne()Executes the SQL statement and returns the first row of the result.Command
queryScalar()Executes the SQL statement and returns the value of the first column in the first row of data.Command
renameColumn()Creates a SQL command for renaming a column.Command
renameTable()Creates a SQL command for renaming a DB table.Command
resetSequence()Creates a SQL command for resetting the sequence value of a table’s primary key.Command
setRawSql()Specifies the SQL statement to be executed. The SQL statement will not be modified in any way.Command
setSql()Specifies the SQL statement to be executed. The SQL statement will be quoted using Connection::quoteSql().Command
trigger()Triggers an event.yii\base\Component
truncateTable()Creates a SQL command for truncating a DB table.Command
update()Creates an UPDATE command.Command
upsert()Creates a command to insert rows into a database table if they do not already exist (matching unique constraints), or update them if they do.Command
bindPendingParams() protectedBinds pending parameters that were registered via bindValue() and bindValues().Command
getCacheKey() protectedReturns the cache key for the query.Command
internalExecute() protectedExecutes a prepared statement.Command
logQuery() protectedLogs the current database query if query logging is enabled and returns the profiling token if profiling is enabled.Command
queryInternal() protectedPerforms the actual DB query of a SQL statement.Command
refreshTableSchema() protectedRefreshes table schema, which was marked by requireTableSchemaRefresh().Command
requireTableSchemaRefresh() protectedMarks a specified table schema to be refreshed after command execution.Command
requireTransaction() protectedMarks the command to be executed in transaction.Command
reset() protectedResets command properties to their initial state.Command
setRetryHandler() protectedSets a callable (e.g. anonymous function) that is called when Exception is thrown when executing the command. The signature of the callable should be:Command
public array $params = []

The parameters (name => value) that are bound to the current PDO statement.

This property is maintained by methods such as bindValue(). It is mainly provided for logging purpose and is used to generate $rawSql. Do not modify it directly.

public int $queryCacheDuration = null

The default number of seconds that query results can remain valid in cache.

Use 0 to indicate that the cached data will never expire. And use a negative number to indicate query cache should not be used.

public function addCheck(string $name, string $table, string $expression): $this

Creates a SQL command for adding a check constraint to an existing table.

Parameters

ParameterTypeDescription
$namestringThe name of the check constraint. The name will be properly quoted by the method.
$tablestringThe table that the check constraint will be added to. The name will be properly quoted by the method.
$expressionstringThe SQL of the CHECK constraint.

Returns

$this: The command object itself.

Since

2.0.13

public function addColumn(string $table, string $column, string $type): $this

Creates a SQL command for adding a new DB column.

Parameters

ParameterTypeDescription
$tablestringThe table that the new column will be added to. The table name will be properly quoted by the method.
$columnstringThe name of the new column. The name will be properly quoted by the method.
$typestringThe column type. QueryBuilder::getColumnType() will be called to convert the given column type to the physical one. For example, string will be converted as varchar(255), and string not null becomes varchar(255) not null.

Returns

$this: The command object itself

public function addCommentOnColumn(string $table, string $column, string $comment): $this

Builds a SQL command for adding comment to column.

Parameters

ParameterTypeDescription
$tablestringThe table whose column is to be commented. The table name will be properly quoted by the method.
$columnstringThe name of the column to be commented. The column name will be properly quoted by the method.
$commentstringThe text of the comment to be added. The comment will be properly quoted by the method.

Returns

$this: The command object itself

Since

2.0.8

public function addCommentOnTable(string $table, string $comment): $this

Builds a SQL command for adding comment to table.

Parameters

ParameterTypeDescription
$tablestringThe table whose column is to be commented. The table name will be properly quoted by the method.
$commentstringThe text of the comment to be added. The comment will be properly quoted by the method.

Returns

$this: The command object itself

Since

2.0.8

public function addDefaultValue(string $name, string $table, string $column, mixed $value): $this

Creates a SQL command for adding a default value constraint to an existing table.

Parameters

ParameterTypeDescription
$namestringThe name of the default value constraint. The name will be properly quoted by the method.
$tablestringThe table that the default value constraint will be added to. The name will be properly quoted by the method.
$columnstringThe name of the column to that the constraint will be added on. The name will be properly quoted by the method.
$valuemixedDefault value.

Returns

$this: The command object itself.

Since

2.0.13

public function addForeignKey(string $name, string $table, string|array $columns, string $refTable, string|array $refColumns, string|null $delete = null, string|null $update = null): $this

Creates a SQL command for adding a foreign key constraint to an existing table.

The method will properly quote the table and column names.

Parameters

ParameterTypeDescription
$namestringThe name of the foreign key constraint.
$tablestringThe table that the foreign key constraint will be added to.
$columnsstring|arrayThe name of the column to that the constraint will be added on. If there are multiple columns, separate them with commas.
$refTablestringThe table that the foreign key references to.
$refColumnsstring|arrayThe name of the column that the foreign key references to. If there are multiple columns, separate them with commas.
$deletestring|nullThe ON DELETE option. Most DBMS support these options: RESTRICT, CASCADE, NO ACTION, SET DEFAULT, SET NULL
$updatestring|nullThe ON UPDATE option. Most DBMS support these options: RESTRICT, CASCADE, NO ACTION, SET DEFAULT, SET NULL

Returns

$this: The command object itself

public function addPrimaryKey(string $name, string $table, string|array $columns): $this

Creates a SQL command for adding a primary key constraint to an existing table.

The method will properly quote the table and column names.

Parameters

ParameterTypeDescription
$namestringThe name of the primary key constraint.
$tablestringThe table that the primary key constraint will be added to.
$columnsstring|arrayComma separated string or array of columns that the primary key will consist of.

Returns

$this: The command object itself.

public function addUnique(string $name, string $table, string|array $columns): $this

Creates a SQL command for adding an unique constraint to an existing table.

Parameters

ParameterTypeDescription
$namestringThe name of the unique constraint. The name will be properly quoted by the method.
$tablestringThe table that the unique constraint will be added to. The name will be properly quoted by the method.
$columnsstring|arrayThe name of the column to that the constraint will be added on. If there are multiple columns, separate them with commas. The name will be properly quoted by the method.

Returns

$this: The command object itself.

Since

2.0.13

public function alterColumn(string $table, string $column, string $type): $this

Creates a SQL command for changing the definition of a column.

Parameters

ParameterTypeDescription
$tablestringThe table whose column is to be changed. The table name will be properly quoted by the method.
$columnstringThe name of the column to be changed. The name will be properly quoted by the method.
$typestringThe column type. QueryBuilder::getColumnType() will be called to convert the give column type to the physical one. For example, string will be converted as varchar(255), and string not null becomes varchar(255) not null.

Returns

$this: The command object itself

public function batchInsert(string $table, array $columns, array|Generator $rows): $this

Creates a batch INSERT command.

For example,

$connection->createCommand()->batchInsert('user', ['name', 'age'], [
['Tom', 30],
['Jane', 20],
['Linda', 25],
])->execute();

The method will properly escape the column names, and quote the values to be inserted.

Note that the values in each row must match the corresponding column names.

Also note that the created command is not executed until execute() is called.

Parameters

ParameterTypeDescription
$tablestringThe table that new rows will be inserted into.
$columnsarrayThe column names
$rowsarray|GeneratorThe rows to be batch inserted into the table

Returns

$this: The command object itself

public function bindParam(string|int $name, mixed &$value, int|null $dataType = null, int|null $length = null, mixed $driverOptions = null): $this

Binds a parameter to the SQL statement to be executed.

Parameters

ParameterTypeDescription
$namestring|intParameter identifier. For a prepared statement using named placeholders, this will be a parameter name of the form :name. For a prepared statement using question mark placeholders, this will be the 1-indexed position of the parameter.
$valuemixedThe PHP variable to bind to the SQL statement parameter (passed by reference)
$dataTypeint|nullSQL data type of the parameter. If null, the type is determined by the PHP type of the value.
$lengthint|nullLength of the data type
$driverOptionsmixedThe driver-specific options

Returns

$this: The current command being executed

See also

public function bindValue(string|int $name, mixed $value, int|null $dataType = null): $this

Binds a value to a parameter.

Parameters

ParameterTypeDescription
$namestring|intParameter identifier. For a prepared statement using named placeholders, this will be a parameter name of the form :name. For a prepared statement using question mark placeholders, this will be the 1-indexed position of the parameter.
$valuemixedThe value to bind to the parameter
$dataTypeint|nullSQL data type of the parameter. If null, the type is determined by the PHP type of the value.

Returns

$this: The current command being executed

See also

public function bindValues(array $values): $this

Binds a list of values to the corresponding parameters.

This is similar to bindValue() except that it binds multiple values at a time. Note that the SQL data type of each value is determined by its PHP type.

Parameters

ParameterTypeDescription
$valuesarrayThe values to be bound. This must be given in terms of an associative array with array keys being the parameter names, and array values the corresponding parameter values, e.g. [':name' => 'John', ':age' => 25]. By default, the PDO type of each value is determined by its PHP type. You may explicitly specify the PDO type by using a PdoValue class: new PdoValue(value, type), e.g. [':name' => 'John', ':profile' => new PdoValue($profile, \PDO::PARAM_LOB)].

Returns

$this: The current command being executed

public function cache(int|null $duration = null, yii\caching\Dependency|null $dependency = null): $this

Enables query cache for this command.

Parameters

ParameterTypeDescription
$durationint|nullThe number of seconds that query result of this command can remain valid in the cache. If this is not set, the value of Connection::$queryCacheDuration will be used instead. Use 0 to indicate that the cached data will never expire.
$dependencyyii\caching\Dependency|nullThe cache dependency associated with the cached query result.

Returns

$this: The command object itself

public function cancel(): mixed

Cancels the execution of the SQL statement.

This method mainly sets $pdoStatement to be null.

Returns

mixed

public function checkIntegrity(bool $check = true, string $schema = '', string $table = ''): $this

Builds a SQL command for enabling or disabling integrity check.

Parameters

ParameterTypeDescription
$checkboolWhether to turn on or off the integrity check.
$schemastringThe schema name of the tables. Defaults to empty string, meaning the current or default schema.
$tablestringThe table name.

Returns

$this: The command object itself

Throws

public function createIndex(string $name, string $table, string|array $columns, bool $unique = false): $this

Creates a SQL command for creating a new index.

Parameters

ParameterTypeDescription
$namestringThe name of the index. The name will be properly quoted by the method.
$tablestringThe table that the new index will be created for. The table name will be properly quoted by the method.
$columnsstring|arrayThe column(s) that should be included in the index. If there are multiple columns, please separate them by commas. The column names will be properly quoted by the method.
$uniqueboolWhether to add UNIQUE constraint on the created index.

Returns

$this: The command object itself

public function createTable(string $table, array $columns, string|null $options = null): $this

Creates a SQL command for creating a new DB table.

The columns in the new table should be specified as name-definition pairs (e.g. ‘name’ => ‘string’), where name stands for a column name which will be properly quoted by the method, and definition stands for the column type which must contain an abstract DB type.

The method QueryBuilder::getColumnType() will be called to convert the abstract column types to physical ones. For example, string will be converted as varchar(255), and string not null becomes varchar(255) not null.

If a column is specified with definition only (e.g. ‘PRIMARY KEY (name, type)’), it will be directly inserted into the generated SQL.

Example usage:

Yii::$app->db->createCommand()->createTable('post', [
'id' => 'pk',
'title' => 'string',
'text' => 'text',
'column_name double precision null default null',
]);

Parameters

ParameterTypeDescription
$tablestringThe name of the table to be created. The name will be properly quoted by the method.
$columnsarrayThe columns (name => definition) in the new table.
$optionsstring|nullAdditional SQL fragment that will be appended to the generated SQL.

Returns

$this: The command object itself

public function createView(string $viewName, string|yii\db\Query $subquery): $this

Creates a SQL View.

Parameters

ParameterTypeDescription
$viewNamestringThe name of the view to be created.
$subquerystring|QueryThe select statement which defines the view. This can be either a string or a Query object.

Returns

$this: The command object itself.

Since

2.0.14

public function delete(string $table, string|array $condition = '', array $params = []): $this

Creates a DELETE command.

For example,

$connection->createCommand()->delete('user', 'status = 0')->execute();

or with using parameter binding for the condition:

$status = 0;
$connection->createCommand()->delete('user', 'status = :status', [':status' => $status])->execute();

The method will properly escape the table and column names.

Note that the created command is not executed until execute() is called.

Parameters

ParameterTypeDescription
$tablestringThe table where the data will be deleted from.
$conditionstring|arrayThe condition that will be put in the WHERE part. Please refer to Query::where() on how to specify condition.
$paramsarrayThe parameters to be bound to the command

Returns

$this: The command object itself

public function dropCheck(string $name, string $table): $this

Creates a SQL command for dropping a check constraint.

Parameters

ParameterTypeDescription
$namestringThe name of the check constraint to be dropped. The name will be properly quoted by the method.
$tablestringThe table whose check constraint is to be dropped. The name will be properly quoted by the method.

Returns

$this: The command object itself.

Since

2.0.13

public function dropColumn(string $table, string $column): $this

Creates a SQL command for dropping a DB column.

Parameters

ParameterTypeDescription
$tablestringThe table whose column is to be dropped. The name will be properly quoted by the method.
$columnstringThe name of the column to be dropped. The name will be properly quoted by the method.

Returns

$this: The command object itself

public function dropCommentFromColumn(string $table, string $column): $this

Builds a SQL command for dropping comment from column.

Parameters

ParameterTypeDescription
$tablestringThe table whose column is to be commented. The table name will be properly quoted by the method.
$columnstringThe name of the column to be commented. The column name will be properly quoted by the method.

Returns

$this: The command object itself

Since

2.0.8

public function dropCommentFromTable(string $table): $this

Builds a SQL command for dropping comment from table.

Parameters

ParameterTypeDescription
$tablestringThe table whose column is to be commented. The table name will be properly quoted by the method.

Returns

$this: The command object itself

Since

2.0.8

public function dropDefaultValue(string $name, string $table): $this

Creates a SQL command for dropping a default value constraint.

Parameters

ParameterTypeDescription
$namestringThe name of the default value constraint to be dropped. The name will be properly quoted by the method.
$tablestringThe table whose default value constraint is to be dropped. The name will be properly quoted by the method.

Returns

$this: The command object itself.

Since

2.0.13

public function dropForeignKey(string $name, string $table): $this

Creates a SQL command for dropping a foreign key constraint.

Parameters

ParameterTypeDescription
$namestringThe name of the foreign key constraint to be dropped. The name will be properly quoted by the method.
$tablestringThe table whose foreign is to be dropped. The name will be properly quoted by the method.

Returns

$this: The command object itself

public function dropIndex(string $name, string $table): $this

Creates a SQL command for dropping an index.

Parameters

ParameterTypeDescription
$namestringThe name of the index to be dropped. The name will be properly quoted by the method.
$tablestringThe table whose index is to be dropped. The name will be properly quoted by the method.

Returns

$this: The command object itself

public function dropPrimaryKey(string $name, string $table): $this

Creates a SQL command for removing a primary key constraint to an existing table.

Parameters

ParameterTypeDescription
$namestringThe name of the primary key constraint to be removed.
$tablestringThe table that the primary key constraint will be removed from.

Returns

$this: The command object itself

public function dropTable(string $table): $this

Creates a SQL command for dropping a DB table.

Parameters

ParameterTypeDescription
$tablestringThe table to be dropped. The name will be properly quoted by the method.

Returns

$this: The command object itself

public function dropUnique(string $name, string $table): $this

Creates a SQL command for dropping an unique constraint.

Parameters

ParameterTypeDescription
$namestringThe name of the unique constraint to be dropped. The name will be properly quoted by the method.
$tablestringThe table whose unique constraint is to be dropped. The name will be properly quoted by the method.

Returns

$this: The command object itself.

Since

2.0.13

public function dropView(string $viewName): $this

Drops a SQL View.

Parameters

ParameterTypeDescription
$viewNamestringThe name of the view to be dropped.

Returns

$this: The command object itself.

Since

2.0.14

public function execute(): int

Executes the SQL statement.

This method should only be used for executing non-query SQL statement, such as INSERT, DELETE, UPDATE SQLs. No result set will be returned.

Returns

int: Number of rows affected by the execution.

Throws

public function executeResetSequence(string $table, int|null $value = null): mixed

Executes a db command resetting the sequence value of a table’s primary key.

Reason for execute is that some databases (Oracle) need several queries to do so.

The sequence is reset such that the primary key of the next new row inserted will have the specified value or the maximum existing value +1.

Parameters

ParameterTypeDescription
$tablestringThe name of the table whose primary key sequence is reset.
$valueint|nullThe integer value for the primary key of the next new row inserted. If this is not set, the next new row’s primary key will have the maximum existing value +1.

Returns

mixed

Throws

Since

2.0.16

public function getRawSql(): string

Returns the raw SQL by inserting parameter values into the corresponding placeholders in $sql.

Note that the return value of this method should mainly be used for logging purpose. It is likely that this method returns an invalid SQL due to improper replacement of parameter placeholders.

Returns

string: The raw SQL with parameter values inserted into the corresponding placeholders in $sql.

public function getSql(): string

Returns the SQL statement for this command.

Returns

string: The SQL statement to be executed

public function insert(string $table, array|yii\db\Query $columns): $this

Creates an INSERT command.

For example,

$connection->createCommand()->insert('user', [
'name' => 'Sam',
'age' => 30,
])->execute();

The method will properly escape the column names, and bind the values to be inserted.

Note that the created command is not executed until execute() is called.

Parameters

ParameterTypeDescription
$tablestringThe table that new rows will be inserted into.
$columnsarray|QueryThe column data (name => value) to be inserted into the table or instance of Query to perform INSERT INTO … SELECT SQL statement. Passing of Query is available since version 2.0.11.

Returns

$this: The command object itself

public function noCache(): $this

Disables query cache for this command.

Returns

$this: The command object itself

public function prepare(bool|null $forRead = null): mixed

Prepares the SQL statement to be executed.

For complex SQL statement that is to be executed multiple times, this may improve performance. For SQL statement with binding parameters, this method is invoked automatically.

Parameters

ParameterTypeDescription
$forReadbool|nullWhether this method is called for a read query. If null, it means the SQL statement should be used to determine whether it is for read or write.

Returns

mixed

Throws

public function query(): yii\db\DataReader

Executes the SQL statement and returns query result.

This method is for executing a SQL query that returns result set, such as SELECT.

Returns

DataReader: The reader object for fetching the query result

Throws

public function queryAll(int|null $fetchMode = null): array

Executes the SQL statement and returns ALL rows at once.

Parameters

ParameterTypeDescription
$fetchModeint|nullThe result fetch mode. Please refer to PHP manual for valid fetch modes. If this parameter is null, the value set in $fetchMode will be used.

Returns

array: All rows of the query result. Each array element is an array representing a row of data. An empty array is returned if the query results in nothing.

Throws

public function queryColumn(): array

Executes the SQL statement and returns the first column of the result.

This method is best used when only the first column of result (i.e. the first element in each row) is needed for a query.

Returns

array: The first column of the query result. Empty array is returned if the query results in nothing.

Throws

public function queryOne(int|null $fetchMode = null): array|false

Executes the SQL statement and returns the first row of the result.

This method is best used when only the first row of result is needed for a query.

Parameters

ParameterTypeDescription
$fetchModeint|nullThe result fetch mode. Please refer to PHP manual for valid fetch modes. If this parameter is null, the value set in $fetchMode will be used.

Returns

array|false: The first row (in terms of an array) of the query result. False is returned if the query results in nothing.

Throws

public function queryScalar(): string|int|null|false

Executes the SQL statement and returns the value of the first column in the first row of data.

This method is best used when only a single value is needed for a query.

Returns

string|int|null|false: The value of the first column in the first row of the query result. False is returned if there is no value.

Throws

public function renameColumn(string $table, string $oldName, string $newName): $this

Creates a SQL command for renaming a column.

Parameters

ParameterTypeDescription
$tablestringThe table whose column is to be renamed. The name will be properly quoted by the method.
$oldNamestringThe old name of the column. The name will be properly quoted by the method.
$newNamestringThe new name of the column. The name will be properly quoted by the method.

Returns

$this: The command object itself

public function renameTable(string $table, string $newName): $this

Creates a SQL command for renaming a DB table.

Parameters

ParameterTypeDescription
$tablestringThe table to be renamed. The name will be properly quoted by the method.
$newNamestringThe new table name. The name will be properly quoted by the method.

Returns

$this: The command object itself

public function resetSequence(string $table, int|null $value = null): $this

Creates a SQL command for resetting the sequence value of a table’s primary key.

The sequence will be reset such that the primary key of the next new row inserted will have the specified value or the maximum existing value +1.

Parameters

ParameterTypeDescription
$tablestringThe name of the table whose primary key sequence will be reset.
$valueint|nullThe integer value for the primary key of the next new row inserted. If this is not set, the next new row’s primary key will have the maximum existing value +1.

Returns

$this: The command object itself.

Throws

public function setRawSql(string $sql): $this

Specifies the SQL statement to be executed. The SQL statement will not be modified in any way.

The previous SQL (if any) will be discarded, and $params will be cleared as well. See reset() for details.

Parameters

ParameterTypeDescription
$sqlstringThe SQL statement to be set.

Returns

$this: This command instance

Since

2.0.13

See also

public function setSql(string $sql): $this

Specifies the SQL statement to be executed. The SQL statement will be quoted using Connection::quoteSql().

The previous SQL (if any) will be discarded, and $params will be cleared as well. See reset() for details.

Parameters

ParameterTypeDescription
$sqlstringThe SQL statement to be set.

Returns

$this: This command instance

See also

public function truncateTable(string $table): $this

Creates a SQL command for truncating a DB table.

Parameters

ParameterTypeDescription
$tablestringThe table to be truncated. The name will be properly quoted by the method.

Returns

$this: The command object itself

public function update(string $table, array $columns, string|array $condition = '', array $params = []): $this

Creates an UPDATE command.

For example,

$connection->createCommand()->update('user', ['status' => 1], 'age > 30')->execute();

or with using parameter binding for the condition:

$minAge = 30;
$connection->createCommand()->update('user', ['status' => 1], 'age > :minAge', [':minAge' => $minAge])->execute();

The method will properly escape the column names and bind the values to be updated.

Note that the created command is not executed until execute() is called.

Parameters

ParameterTypeDescription
$tablestringThe table to be updated.
$columnsarrayThe column data (name => value) to be updated.
$conditionstring|arrayThe condition that will be put in the WHERE part. Please refer to Query::where() on how to specify condition.
$paramsarrayThe parameters to be bound to the command

Returns

$this: The command object itself

public function upsert(string $table, array|yii\db\Query $insertColumns, array|bool $updateColumns = true, array $params = []): $this

Creates a command to insert rows into a database table if they do not already exist (matching unique constraints), or update them if they do.

For example,

$sql = $queryBuilder->upsert('pages', [
'name' => 'Front page',
'url' => 'https://example.com/', // url is unique
'visits' => 0,
], [
'visits' => new \yii\db\Expression('visits + 1'),
], $params);

The method will properly escape the table and column names.

Parameters

ParameterTypeDescription
$tablestringThe table that new rows will be inserted into/updated in.
$insertColumnsarray|QueryThe column data (name => value) to be inserted into the table or instance of Query to perform INSERT INTO ... SELECT SQL statement.
$updateColumnsarray|boolThe column data (name => value) to be updated if they already exist. If true is passed, the column data will be updated to match the insert column data. If false is passed, no update will be performed if the column data already exists.
$paramsarrayThe parameters to be bound to the command.

Returns

$this: The command object itself.

Since

2.0.14

protected function bindPendingParams(): mixed

Binds pending parameters that were registered via bindValue() and bindValues().

Note that this method requires an active $pdoStatement.

Returns

mixed

protected function getCacheKey(string $method, int $fetchMode, mixed $rawSql): array

Returns the cache key for the query.

Parameters

ParameterTypeDescription
$methodstringMethod of PDOStatement to be called
$fetchModeintThe result fetch mode. Please refer to PHP manual for valid fetch modes.
$rawSqlmixed

Returns

array: The cache key

Since

2.0.16

protected function internalExecute(string|null $rawSql): mixed

Executes a prepared statement.

It’s a wrapper around PDOStatement::execute() to support transactions and retry handlers.

Parameters

ParameterTypeDescription
$rawSqlstring|nullThe rawSql if it has been created.

Returns

mixed

Throws

Since

2.0.14

protected function logQuery(string $category): array

Logs the current database query if query logging is enabled and returns the profiling token if profiling is enabled.

Parameters

ParameterTypeDescription
$categorystringThe log category.

Returns

array: Array of two elements, the first is boolean of whether profiling is enabled or not. The second is the rawSql if it has been created.

protected function queryInternal(string $method, int|null $fetchMode = null): mixed

Performs the actual DB query of a SQL statement.

Parameters

ParameterTypeDescription
$methodstringMethod of PDOStatement to be called
$fetchModeint|nullThe result fetch mode. Please refer to PHP manual for valid fetch modes. If this parameter is null, the value set in $fetchMode will be used.

Returns

mixed: The method execution result

Throws

protected function refreshTableSchema(): mixed

Refreshes table schema, which was marked by requireTableSchemaRefresh().

Returns

mixed

Since

2.0.6

protected function requireTableSchemaRefresh(string $name): $this

Marks a specified table schema to be refreshed after command execution.

Parameters

ParameterTypeDescription
$namestringName of the table, which schema should be refreshed.

Returns

$this: This command instance

Since

2.0.6

protected function requireTransaction(string|null $isolationLevel = null): $this

Marks the command to be executed in transaction.

Parameters

ParameterTypeDescription
$isolationLevelstring|nullThe isolation level to use for this transaction. See Transaction::begin() for details.

Returns

$this: This command instance.

Since

2.0.14

protected function reset(): mixed

Resets command properties to their initial state.

Returns

mixed

Since

2.0.13

protected function setRetryHandler(callable $handler): $this

Sets a callable (e.g. anonymous function) that is called when Exception is thrown when executing the command. The signature of the callable should be:

function (\yii\db\Exception $e, $attempt)
{
// return true or false (whether to retry the command or rethrow $e)
}

The callable will receive a database exception thrown and a current attempt (to execute the command) number starting from 1.

Parameters

ParameterTypeDescription
$handlercallableA PHP callback to handle database exceptions.

Returns

$this: This command instance.

Since

2.0.14