PHP Class yii\db\Command

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 Command::execute. To execute a SQL statement that returns result data set (such as SELECT), use Command::queryAll, Command::queryOne, Command::queryColumn, Command::queryScalar, or Command::query. For example, ~~~ $users = $connection->createCommand('SELECT * FROM user')->queryAll(); ~~~ Command supports SQL statement preparation and parameter binding. Call Command::bindValue to bind a value to a SQL parameter; Call Command::bindParam to bind a PHP variable to a SQL parameter. When binding a parameter, the SQL statement is automatically prepared. You may also call Command::prepare explicitly to prepare a SQL statement. Command also supports building SQL statements by providing methods such as Command::insert, Command::update, etc. For example, ~~~ $connection->createCommand()->insert('user', [ 'name' => 'Sam', 'age' => 30, ])->execute(); ~~~ To build SELECT SQL statements, please use QueryBuilder instead.
Since: 2.0
Author: Qiang Xue ([email protected])
Inheritance: extends yii\base\Component
Datei anzeigen Open project: yiisoft/yii2 Class Usage Examples

Public Properties

Property Type Description
$db the DB connection that this command is associated with
$fetchMode the default fetch mode for this command.
$params the parameters (name => value) that are bound to the current PDO statement. This property is maintained by methods such as Command::bindValue. It is mainly provided for logging purpose and is used to generate [[rawSql]]. Do not modify it directly.
$pdoStatement the PDOStatement object that this command is associated with
$queryCacheDependency the dependency to be associated with the cached query result for this command
$queryCacheDuration 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 Methods

Method Description
addColumn ( string $table, string $column, string $type ) Creates a SQL command for adding a new DB column.
addCommentOnColumn ( string $table, string $column, string $comment ) Builds a SQL command for adding comment to column
addCommentOnTable ( string $table, string $comment ) Builds a SQL command for adding comment to table
addForeignKey ( string $name, string $table, string | array $columns, string $refTable, string | array $refColumns, string $delete = null, string $update = null ) Creates a SQL command for adding a foreign key constraint to an existing table.
addPrimaryKey ( string $name, string $table, string | array $columns ) Creates a SQL command for adding a primary key constraint to an existing table.
alterColumn ( string $table, string $column, string $type ) Creates a SQL command for changing the definition of a column.
batchInsert ( string $table, array $columns, array $rows ) Creates a batch INSERT command.
bindParam ( string | integer $name, mixed &$value, integer $dataType = null, integer $length = null, mixed $driverOptions = null ) Binds a parameter to the SQL statement to be executed.
bindValue ( string | integer $name, mixed $value, integer $dataType = null ) Binds a value to a parameter.
bindValues ( array $values ) Binds a list of values to the corresponding parameters.
cache ( integer $duration = null, yii\caching\Dependency $dependency = null ) Enables query cache for this command.
cancel ( ) Cancels the execution of the SQL statement.
checkIntegrity ( boolean $check = true, string $schema = '', string $table = '' ) Builds a SQL command for enabling or disabling integrity check.
createIndex ( string $name, string $table, string | array $columns, boolean $unique = false ) Creates a SQL command for creating a new index.
createTable ( string $table, array $columns, string $options = null ) Creates a SQL command for creating a new DB table.
delete ( string $table, string | array $condition = '', array $params = [] ) Creates a DELETE command.
dropColumn ( string $table, string $column ) Creates a SQL command for dropping a DB column.
dropCommentFromColumn ( string $table, string $column ) Builds a SQL command for dropping comment from column
dropCommentFromTable ( string $table ) Builds a SQL command for dropping comment from table
dropForeignKey ( string $name, string $table ) Creates a SQL command for dropping a foreign key constraint.
dropIndex ( string $name, string $table ) Creates a SQL command for dropping an index.
dropPrimaryKey ( string $name, string $table ) Creates a SQL command for removing a primary key constraint to an existing table.
dropTable ( string $table ) Creates a SQL command for dropping a DB table.
execute ( ) : integer Executes the SQL statement.
getRawSql ( ) : string Returns the raw SQL by inserting parameter values into the corresponding placeholders in [[sql]].
getSql ( ) : string Returns the SQL statement for this command.
insert ( string $table, array $columns ) Creates an INSERT command.
noCache ( ) Disables query cache for this command.
prepare ( boolean $forRead = null ) Prepares the SQL statement to be executed.
query ( ) : DataReader Executes the SQL statement and returns query result.
queryAll ( integer $fetchMode = null ) : array Executes the SQL statement and returns ALL rows at once.
queryColumn ( ) : array Executes the SQL statement and returns the first column of the result.
queryOne ( integer $fetchMode = null ) : array | false Executes the SQL statement and returns the first row of the result.
queryScalar ( ) : string | null | false Executes the SQL statement and returns the value of the first column in the first row of data.
renameColumn ( string $table, string $oldName, string $newName ) Creates a SQL command for renaming a column.
renameTable ( string $table, string $newName ) Creates a SQL command for renaming a DB table.
resetSequence ( string $table, mixed $value = null ) Creates a SQL command for resetting the sequence value of a table's primary key.
setSql ( string $sql ) Specifies the SQL statement to be executed.
truncateTable ( string $table ) Creates a SQL command for truncating a DB table.
update ( string $table, array $columns, string | array $condition = '', array $params = [] ) Creates an UPDATE command.

Protected Methods

Method Description
bindPendingParams ( ) Binds pending parameters that were registered via Command::bindValue and Command::bindValues.
queryInternal ( string $method, integer $fetchMode = null ) : mixed Performs the actual DB query of a SQL statement.
refreshTableSchema ( ) Refreshes table schema, which was marked by Command::requireTableSchemaRefresh
requireTableSchemaRefresh ( string $name ) Marks a specified table schema to be refreshed after command execution.

Method Details

addColumn() public method

Creates a SQL command for adding a new DB column.
public addColumn ( string $table, string $column, string $type )
$table string the table that the new column will be added to. The table name will be properly quoted by the method.
$column string the name of the new column. The name will be properly quoted by the method.
$type string the column type. [[\yii\db\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`.

addCommentOnColumn() public method

Builds a SQL command for adding comment to column
Since: 2.0.8
public addCommentOnColumn ( string $table, string $column, string $comment )
$table string the table whose column is to be commented. The table name will be properly quoted by the method.
$column string the name of the column to be commented. The column name will be properly quoted by the method.
$comment string the text of the comment to be added. The comment will be properly quoted by the method.

addCommentOnTable() public method

Builds a SQL command for adding comment to table
Since: 2.0.8
public addCommentOnTable ( string $table, string $comment )
$table string the table whose column is to be commented. The table name will be properly quoted by the method.
$comment string the text of the comment to be added. The comment will be properly quoted by the method.

addForeignKey() public method

The method will properly quote the table and column names.
public addForeignKey ( string $name, string $table, string | array $columns, string $refTable, string | array $refColumns, string $delete = null, string $update = null )
$name string the name of the foreign key constraint.
$table string the table that the foreign key constraint will be added to.
$columns string | array the name of the column to that the constraint will be added on. If there are multiple columns, separate them with commas.
$refTable string the table that the foreign key references to.
$refColumns string | array the name of the column that the foreign key references to. If there are multiple columns, separate them with commas.
$delete string the ON DELETE option. Most DBMS support these options: RESTRICT, CASCADE, NO ACTION, SET DEFAULT, SET NULL
$update string the ON UPDATE option. Most DBMS support these options: RESTRICT, CASCADE, NO ACTION, SET DEFAULT, SET NULL

addPrimaryKey() public method

The method will properly quote the table and column names.
public addPrimaryKey ( string $name, string $table, string | array $columns )
$name string the name of the primary key constraint.
$table string the table that the primary key constraint will be added to.
$columns string | array comma separated string or array of columns that the primary key will consist of.

alterColumn() public method

Creates a SQL command for changing the definition of a column.
public alterColumn ( string $table, string $column, string $type )
$table string the table whose column is to be changed. The table name will be properly quoted by the method.
$column string the name of the column to be changed. The name will be properly quoted by the method.
$type string the column type. [[\yii\db\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`.

batchInsert() public method

For example, php $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 Command::execute is called.
public batchInsert ( string $table, array $columns, array $rows )
$table string the table that new rows will be inserted into.
$columns array the column names
$rows array the rows to be batch inserted into the table

bindParam() public method

Binds a parameter to the SQL statement to be executed.
See also: http://www.php.net/manual/en/function.PDOStatement-bindParam.php
public bindParam ( string | integer $name, mixed &$value, integer $dataType = null, integer $length = null, mixed $driverOptions = null )
$name string | integer parameter 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.
$value mixed the PHP variable to bind to the SQL statement parameter (passed by reference)
$dataType integer SQL data type of the parameter. If null, the type is determined by the PHP type of the value.
$length integer length of the data type
$driverOptions mixed the driver-specific options

bindPendingParams() protected method

Note that this method requires an active [[pdoStatement]].
protected bindPendingParams ( )

bindValue() public method

Binds a value to a parameter.
See also: http://www.php.net/manual/en/function.PDOStatement-bindValue.php
public bindValue ( string | integer $name, mixed $value, integer $dataType = null )
$name string | integer Parameter 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.
$value mixed The value to bind to the parameter
$dataType integer SQL data type of the parameter. If null, the type is determined by the PHP type of the value.

bindValues() public method

This is similar to Command::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.
public bindValues ( array $values )
$values array the 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 an array: `[value, type]`, e.g. `[':name' => 'John', ':profile' => [$profile, \PDO::PARAM_LOB]]`.

cache() public method

Enables query cache for this command.
public cache ( integer $duration = null, yii\caching\Dependency $dependency = null )
$duration integer the 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.
$dependency yii\caching\Dependency the cache dependency associated with the cached query result.

cancel() public method

This method mainly sets [[pdoStatement]] to be null.
public cancel ( )

checkIntegrity() public method

Builds a SQL command for enabling or disabling integrity check.
public checkIntegrity ( boolean $check = true, string $schema = '', string $table = '' )
$check boolean whether to turn on or off the integrity check.
$schema string the schema name of the tables. Defaults to empty string, meaning the current or default schema.
$table string the table name.

createIndex() public method

Creates a SQL command for creating a new index.
public createIndex ( string $name, string $table, string | array $columns, boolean $unique = false )
$name string the name of the index. The name will be properly quoted by the method.
$table string the table that the new index will be created for. The table name will be properly quoted by the method.
$columns string | array the 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.
$unique boolean whether to add UNIQUE constraint on the created index.

createTable() public method

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 can 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.
public createTable ( string $table, array $columns, string $options = null )
$table string the name of the table to be created. The name will be properly quoted by the method.
$columns array the columns (name => definition) in the new table.
$options string additional SQL fragment that will be appended to the generated SQL.

delete() public method

For example, php $connection->createCommand()->delete('user', 'status = 0')->execute(); The method will properly escape the table and column names. Note that the created command is not executed until Command::execute is called.
public delete ( string $table, string | array $condition = '', array $params = [] )
$table string the table where the data will be deleted from.
$condition string | array the condition that will be put in the WHERE part. Please refer to [[Query::where()]] on how to specify condition.
$params array the parameters to be bound to the command

dropColumn() public method

Creates a SQL command for dropping a DB column.
public dropColumn ( string $table, string $column )
$table string the table whose column is to be dropped. The name will be properly quoted by the method.
$column string the name of the column to be dropped. The name will be properly quoted by the method.

dropCommentFromColumn() public method

Builds a SQL command for dropping comment from column
Since: 2.0.8
public dropCommentFromColumn ( string $table, string $column )
$table string the table whose column is to be commented. The table name will be properly quoted by the method.
$column string the name of the column to be commented. The column name will be properly quoted by the method.

dropCommentFromTable() public method

Builds a SQL command for dropping comment from table
Since: 2.0.8
public dropCommentFromTable ( string $table )
$table string the table whose column is to be commented. The table name will be properly quoted by the method.

dropForeignKey() public method

Creates a SQL command for dropping a foreign key constraint.
public dropForeignKey ( string $name, string $table )
$name string the name of the foreign key constraint to be dropped. The name will be properly quoted by the method.
$table string the table whose foreign is to be dropped. The name will be properly quoted by the method.

dropIndex() public method

Creates a SQL command for dropping an index.
public dropIndex ( string $name, string $table )
$name string the name of the index to be dropped. The name will be properly quoted by the method.
$table string the table whose index is to be dropped. The name will be properly quoted by the method.

dropPrimaryKey() public method

Creates a SQL command for removing a primary key constraint to an existing table.
public dropPrimaryKey ( string $name, string $table )
$name string the name of the primary key constraint to be removed.
$table string the table that the primary key constraint will be removed from.

dropTable() public method

Creates a SQL command for dropping a DB table.
public dropTable ( string $table )
$table string the table to be dropped. The name will be properly quoted by the method.

execute() public method

This method should only be used for executing non-query SQL statement, such as INSERT, DELETE, UPDATE SQLs. No result set will be returned.
public execute ( ) : integer
return integer number of rows affected by the execution.

getRawSql() public method

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.
public getRawSql ( ) : string
return string the raw SQL with parameter values inserted into the corresponding placeholders in [[sql]].

getSql() public method

Returns the SQL statement for this command.
public getSql ( ) : string
return string the SQL statement to be executed

insert() public method

For example, php $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 Command::execute is called.
public insert ( string $table, array $columns )
$table string the table that new rows will be inserted into.
$columns array the column data (name => value) to be inserted into the table.

noCache() public method

Disables query cache for this command.
public noCache ( )

prepare() public method

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.
public prepare ( boolean $forRead = null )
$forRead boolean whether 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.

query() public method

This method is for executing a SQL query that returns result set, such as SELECT.
public query ( ) : DataReader
return DataReader the reader object for fetching the query result

queryAll() public method

Executes the SQL statement and returns ALL rows at once.
public queryAll ( integer $fetchMode = null ) : array
$fetchMode integer the result fetch mode. Please refer to [PHP manual](http://www.php.net/manual/en/function.PDOStatement-setFetchMode.php) for valid fetch modes. If this parameter is null, the value set in [[fetchMode]] will be used.
return 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.

queryColumn() public method

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.
public queryColumn ( ) : array
return array the first column of the query result. Empty array is returned if the query results in nothing.

queryInternal() protected method

Performs the actual DB query of a SQL statement.
Since: 2.0.1 this method is protected (was private before).
protected queryInternal ( string $method, integer $fetchMode = null ) : mixed
$method string method of PDOStatement to be called
$fetchMode integer the result fetch mode. Please refer to [PHP manual](http://www.php.net/manual/en/function.PDOStatement-setFetchMode.php) for valid fetch modes. If this parameter is null, the value set in [[fetchMode]] will be used.
return mixed the method execution result

queryOne() public method

This method is best used when only the first row of result is needed for a query.
public queryOne ( integer $fetchMode = null ) : array | false
$fetchMode integer the result fetch mode. Please refer to [PHP manual](http://www.php.net/manual/en/function.PDOStatement-setFetchMode.php) for valid fetch modes. If this parameter is null, the value set in [[fetchMode]] will be used.
return array | false the first row (in terms of an array) of the query result. False is returned if the query results in nothing.

queryScalar() public method

This method is best used when only a single value is needed for a query.
public queryScalar ( ) : string | null | false
return string | null | false the value of the first column in the first row of the query result. False is returned if there is no value.

refreshTableSchema() protected method

Refreshes table schema, which was marked by Command::requireTableSchemaRefresh
Since: 2.0.6
protected refreshTableSchema ( )

renameColumn() public method

Creates a SQL command for renaming a column.
public renameColumn ( string $table, string $oldName, string $newName )
$table string the table whose column is to be renamed. The name will be properly quoted by the method.
$oldName string the old name of the column. The name will be properly quoted by the method.
$newName string the new name of the column. The name will be properly quoted by the method.

renameTable() public method

Creates a SQL command for renaming a DB table.
public renameTable ( string $table, string $newName )
$table string the table to be renamed. The name will be properly quoted by the method.
$newName string the new table name. The name will be properly quoted by the method.

requireTableSchemaRefresh() protected method

Marks a specified table schema to be refreshed after command execution.
Since: 2.0.6
protected requireTableSchemaRefresh ( string $name )
$name string name of the table, which schema should be refreshed.

resetSequence() public method

The sequence will be reset such that the primary key of the next new row inserted will have the specified value or 1.
public resetSequence ( string $table, mixed $value = null )
$table string the name of the table whose primary key sequence will be reset
$value mixed the 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 a value 1.

setSql() public method

The previous SQL execution (if any) will be cancelled, and [[params]] will be cleared as well.
public setSql ( string $sql )
$sql string the SQL statement to be set.

truncateTable() public method

Creates a SQL command for truncating a DB table.
public truncateTable ( string $table )
$table string the table to be truncated. The name will be properly quoted by the method.

update() public method

For example, php $connection->createCommand()->update('user', ['status' => 1], 'age > 30')->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 Command::execute is called.
public update ( string $table, array $columns, string | array $condition = '', array $params = [] )
$table string the table to be updated.
$columns array the column data (name => value) to be updated.
$condition string | array the condition that will be put in the WHERE part. Please refer to [[Query::where()]] on how to specify condition.
$params array the parameters to be bound to the command

Property Details

$db public_oe property

the DB connection that this command is associated with
public $db

$fetchMode public_oe property

the default fetch mode for this command.
See also: http://www.php.net/manual/en/function.PDOStatement-setFetchMode.php
public $fetchMode

$params public_oe property

the parameters (name => value) that are bound to the current PDO statement. This property is maintained by methods such as Command::bindValue. It is mainly provided for logging purpose and is used to generate [[rawSql]]. Do not modify it directly.
public $params

$pdoStatement public_oe property

the PDOStatement object that this command is associated with
public $pdoStatement

$queryCacheDependency public_oe property

the dependency to be associated with the cached query result for this command
See also: cache()
public $queryCacheDependency

$queryCacheDuration public_oe property

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.
See also: cache()
public $queryCacheDuration