Class yii\db\Command
Inheritance | yii\db\Command » yii\base\Component » yii\base\BaseObject |
---|---|
Implements | yii\base\Configurable |
Subclasses | yii\db\sqlite\Command, yii\sphinx\Command |
Available since version | 2.0 |
Source Code | https://github.com/yiisoft/yii2/blob/master/framework/db/Command.php |
Command represents a SQL statement to be executed against a database.
A command object is usually created by calling yii\db\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 yii\db\Query instead.
For more details and usage information on Command, see the guide article on Database Access Objects.
Public Properties
Property | Type | Description | Defined By |
---|---|---|---|
$behaviors | yii\base\Behavior[] | List of behaviors attached to this component | yii\base\Component |
$db | yii\db\Connection | The DB connection that this command is associated with | yii\db\Command |
$fetchMode | integer | The default fetch mode for this command. | yii\db\Command |
$params | array | The parameters (name => value) that are bound to the current PDO statement. | yii\db\Command |
$pdoStatement | PDOStatement | The PDOStatement object that this command is associated with | yii\db\Command |
$queryCacheDependency | yii\caching\Dependency | The dependency to be associated with the cached query result for this command | yii\db\Command |
$queryCacheDuration | integer | The default number of seconds that query results can remain valid in cache. | yii\db\Command |
$rawSql | string | The SQL statement to be set. | yii\db\Command |
$sql | string | The SQL statement to be executed | yii\db\Command |
Public Methods
Method | Description | Defined By |
---|---|---|
__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 |
__construct() | Constructor. | yii\base\BaseObject |
__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. | yii\db\Command |
addColumn() | Creates a SQL command for adding a new DB column. | yii\db\Command |
addCommentOnColumn() | Builds a SQL command for adding comment to column. | yii\db\Command |
addCommentOnTable() | Builds a SQL command for adding comment to table. | yii\db\Command |
addDefaultValue() | Creates a SQL command for adding a default value constraint to an existing table. | yii\db\Command |
addForeignKey() | Creates a SQL command for adding a foreign key constraint to an existing table. | yii\db\Command |
addPrimaryKey() | Creates a SQL command for adding a primary key constraint to an existing table. | yii\db\Command |
addUnique() | Creates a SQL command for adding an unique constraint to an existing table. | yii\db\Command |
alterColumn() | Creates a SQL command for changing the definition of a column. | yii\db\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. | yii\db\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. | yii\db\Command |
bindValue() | Binds a value to a parameter. | yii\db\Command |
bindValues() | Binds a list of values to the corresponding parameters. | yii\db\Command |
cache() | Enables query cache for this command. | yii\db\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 |
cancel() | Cancels the execution of the SQL statement. | yii\db\Command |
checkIntegrity() | Builds a SQL command for enabling or disabling integrity check. | yii\db\Command |
className() | Returns the fully qualified name of this class. | yii\base\BaseObject |
createIndex() | Creates a SQL command for creating a new index. | yii\db\Command |
createTable() | Creates a SQL command for creating a new DB table. | yii\db\Command |
createView() | Creates a SQL View. | yii\db\Command |
delete() | Creates a DELETE command. | yii\db\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. | yii\db\Command |
dropColumn() | Creates a SQL command for dropping a DB column. | yii\db\Command |
dropCommentFromColumn() | Builds a SQL command for dropping comment from column. | yii\db\Command |
dropCommentFromTable() | Builds a SQL command for dropping comment from table. | yii\db\Command |
dropDefaultValue() | Creates a SQL command for dropping a default value constraint. | yii\db\Command |
dropForeignKey() | Creates a SQL command for dropping a foreign key constraint. | yii\db\Command |
dropIndex() | Creates a SQL command for dropping an index. | yii\db\Command |
dropPrimaryKey() | Creates a SQL command for removing a primary key constraint to an existing table. | yii\db\Command |
dropTable() | Creates a SQL command for dropping a DB table. | yii\db\Command |
dropUnique() | Creates a SQL command for dropping an unique constraint. | yii\db\Command |
dropView() | Drops a SQL View. | yii\db\Command |
ensureBehaviors() | Makes sure that the behaviors declared in behaviors() are attached to this component. | yii\base\Component |
execute() | Executes the SQL statement. | yii\db\Command |
executeResetSequence() | Executes a db command resetting the sequence value of a table's primary key. | yii\db\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. | yii\db\Command |
getSql() | Returns the SQL statement for this command. | yii\db\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. | yii\db\Command |
noCache() | Disables query cache for this command. | yii\db\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. | yii\db\Command |
query() | Executes the SQL statement and returns query result. | yii\db\Command |
queryAll() | Executes the SQL statement and returns ALL rows at once. | yii\db\Command |
queryColumn() | Executes the SQL statement and returns the first column of the result. | yii\db\Command |
queryOne() | Executes the SQL statement and returns the first row of the result. | yii\db\Command |
queryScalar() | Executes the SQL statement and returns the value of the first column in the first row of data. | yii\db\Command |
renameColumn() | Creates a SQL command for renaming a column. | yii\db\Command |
renameTable() | Creates a SQL command for renaming a DB table. | yii\db\Command |
resetSequence() | Creates a SQL command for resetting the sequence value of a table's primary key. | yii\db\Command |
setRawSql() | Specifies the SQL statement to be executed. The SQL statement will not be modified in any way. | yii\db\Command |
setSql() | Specifies the SQL statement to be executed. The SQL statement will be quoted using yii\db\Connection::quoteSql(). | yii\db\Command |
trigger() | Triggers an event. | yii\base\Component |
truncateTable() | Creates a SQL command for truncating a DB table. | yii\db\Command |
update() | Creates an UPDATE command. | yii\db\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. | yii\db\Command |
Protected Methods
Method | Description | Defined By |
---|---|---|
bindPendingParams() | Binds pending parameters that were registered via bindValue() and bindValues(). | yii\db\Command |
getCacheKey() | Returns the cache key for the query. | yii\db\Command |
internalExecute() | Executes a prepared statement. | yii\db\Command |
logQuery() | Logs the current database query if query logging is enabled and returns the profiling token if profiling is enabled. | yii\db\Command |
queryInternal() | Performs the actual DB query of a SQL statement. | yii\db\Command |
refreshTableSchema() | Refreshes table schema, which was marked by requireTableSchemaRefresh(). | yii\db\Command |
requireTableSchemaRefresh() | Marks a specified table schema to be refreshed after command execution. | yii\db\Command |
requireTransaction() | Marks the command to be executed in transaction. | yii\db\Command |
reset() | Resets command properties to their initial state. | yii\db\Command |
setRetryHandler() | Sets a callable (e.g. anonymous function) that is called when yii\db\Exception is thrown when executing the command. The signature of the callable should be: | yii\db\Command |
Property Details
The DB connection that this command is associated with
The default fetch mode for this command.
See also http://www.php.net/manual/en/pdostatement.setfetchmode.php.
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.
The PDOStatement object that this command is associated with
The dependency to be associated with the cached query result for this command
See also cache().
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().
The SQL statement to be set.
The SQL statement to be executed
Method Details
Creates a SQL command for adding a check constraint to an existing table.
public $this addCheck ( $name, $table, $expression ) | ||
$name | string | The name of the check constraint. The name will be properly quoted by the method. |
$table | string | The table that the check constraint will be added to. The name will be properly quoted by the method. |
$expression | string | The SQL of the |
return | $this | The command object itself. |
---|
Creates a SQL command for adding a new DB column.
public $this addColumn ( $table, $column, $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, |
return | $this | The command object itself |
---|
Builds a SQL command for adding comment to column.
public $this addCommentOnColumn ( $table, $column, $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. |
return | $this | The command object itself |
---|
Builds a SQL command for adding comment to table.
public $this addCommentOnTable ( $table, $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. |
return | $this | The command object itself |
---|
Creates a SQL command for adding a default value constraint to an existing table.
public $this addDefaultValue ( $name, $table, $column, $value ) | ||
$name | string | The name of the default value constraint. The name will be properly quoted by the method. |
$table | string | The table that the default value constraint will be added to. The name will be properly quoted by the method. |
$column | string | The name of the column to that the constraint will be added on. The name will be properly quoted by the method. |
$value | mixed | Default value. |
return | $this | The command object itself. |
---|
Creates a SQL command for adding a foreign key constraint to an existing table.
The method will properly quote the table and column names.
public $this addForeignKey ( $name, $table, $columns, $refTable, $refColumns, $delete = null, $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 |
return | $this | The command object itself |
---|
Creates a SQL command for adding a primary key constraint to an existing table.
The method will properly quote the table and column names.
public $this addPrimaryKey ( $name, $table, $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. |
return | $this | The command object itself. |
---|
Creates a SQL command for adding an unique constraint to an existing table.
public $this addUnique ( $name, $table, $columns ) | ||
$name | string | The name of the unique constraint. The name will be properly quoted by the method. |
$table | string | The table that the unique constraint will be added to. The name will be properly quoted by the method. |
$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. The name will be properly quoted by the method. |
return | $this | The command object itself. |
---|
Creates a SQL command for changing the definition of a column.
public $this alterColumn ( $table, $column, $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, |
return | $this | The command object itself |
---|
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.
public $this batchInsert ( $table, $columns, $rows ) | ||
$table | string | The table that new rows will be inserted into. |
$columns | array | The column names |
$rows | array|Generator | The rows to be batch inserted into the table |
return | $this | The command object itself |
---|
Binds a parameter to the SQL statement to be executed.
See also http://www.php.net/manual/en/function.PDOStatement-bindParam.php.
public $this bindParam ( $name, &$value, $dataType = null, $length = null, $driverOptions = null ) | ||
$name | string|integer | Parameter identifier. For a prepared statement
using named placeholders, this will be a parameter name of
the form |
$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 |
return | $this | The current command being executed |
---|
Binds pending parameters that were registered via bindValue() and bindValues().
Note that this method requires an active $pdoStatement.
protected void bindPendingParams ( ) |
Binds a value to a parameter.
See also http://www.php.net/manual/en/function.PDOStatement-bindValue.php.
public $this bindValue ( $name, $value, $dataType = null ) | ||
$name | string|integer | Parameter identifier. For a prepared statement
using named placeholders, this will be a parameter name of
the form |
$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. |
return | $this | The current command being executed |
---|
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.
public $this bindValues ( $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. |
return | $this | The current command being executed |
---|
Enables query cache for this command.
public $this cache ( $duration = null, $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 yii\db\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. |
return | $this | The command object itself |
---|
Cancels the execution of the SQL statement.
This method mainly sets $pdoStatement to be null.
public void cancel ( ) |
Builds a SQL command for enabling or disabling integrity check.
public $this checkIntegrity ( $check = true, $schema = '', $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. |
return | $this | The command object itself |
---|---|---|
throws | yii\base\NotSupportedException | if this is not supported by the underlying DBMS |
Creates a SQL command for creating a new index.
public $this createIndex ( $name, $table, $columns, $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. |
return | $this | The command object itself |
---|
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 can contain an abstract DB type.
The method yii\db\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 $this createTable ( $table, $columns, $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. |
return | $this | The command object itself |
---|
Creates a SQL View.
public $this createView ( $viewName, $subquery ) | ||
$viewName | string | The name of the view to be created. |
$subquery | string|yii\db\Query | The select statement which defines the view. This can be either a string or a yii\db\Query object. |
return | $this | The command object itself. |
---|
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.
public $this delete ( $table, $condition = '', $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 yii\db\Query::where() on how to specify condition. |
$params | array | The parameters to be bound to the command |
return | $this | The command object itself |
---|
Creates a SQL command for dropping a check constraint.
public $this dropCheck ( $name, $table ) | ||
$name | string | The name of the check constraint to be dropped. The name will be properly quoted by the method. |
$table | string | The table whose check constraint is to be dropped. The name will be properly quoted by the method. |
return | $this | The command object itself. |
---|
Creates a SQL command for dropping a DB column.
public $this dropColumn ( $table, $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. |
return | $this | The command object itself |
---|
Builds a SQL command for dropping comment from column.
public $this dropCommentFromColumn ( $table, $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. |
return | $this | The command object itself |
---|
Builds a SQL command for dropping comment from table.
public $this dropCommentFromTable ( $table ) | ||
$table | string | The table whose column is to be commented. The table name will be properly quoted by the method. |
return | $this | The command object itself |
---|
Creates a SQL command for dropping a default value constraint.
public $this dropDefaultValue ( $name, $table ) | ||
$name | string | The name of the default value constraint to be dropped. The name will be properly quoted by the method. |
$table | string | The table whose default value constraint is to be dropped. The name will be properly quoted by the method. |
return | $this | The command object itself. |
---|
Creates a SQL command for dropping a foreign key constraint.
public $this dropForeignKey ( $name, $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. |
return | $this | The command object itself |
---|
Creates a SQL command for dropping an index.
public $this dropIndex ( $name, $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. |
return | $this | The command object itself |
---|
Creates a SQL command for removing a primary key constraint to an existing table.
public $this dropPrimaryKey ( $name, $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. |
return | $this | The command object itself |
---|
Creates a SQL command for dropping a DB table.
public $this dropTable ( $table ) | ||
$table | string | The table to be dropped. The name will be properly quoted by the method. |
return | $this | The command object itself |
---|
Creates a SQL command for dropping an unique constraint.
public $this dropUnique ( $name, $table ) | ||
$name | string | The name of the unique constraint to be dropped. The name will be properly quoted by the method. |
$table | string | The table whose unique constraint is to be dropped. The name will be properly quoted by the method. |
return | $this | The command object itself. |
---|
Drops a SQL View.
public $this dropView ( $viewName ) | ||
$viewName | string | The name of the view to be dropped. |
return | $this | The command object itself. |
---|
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.
public integer execute ( ) | ||
return | integer | Number of rows affected by the execution. |
---|---|---|
throws | yii\db\Exception | execution failed |
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.
public void executeResetSequence ( $table, $value = null ) | ||
$table | string | The name of the table whose primary key sequence is 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 the maximum existing value +1. |
throws | yii\base\NotSupportedException | if this is not supported by the underlying DBMS |
---|
Returns the cache key for the query.
protected array getCacheKey ( $method, $fetchMode, $rawSql ) | ||
$method | string | Method of PDOStatement to be called |
$fetchMode | integer | The result fetch mode. Please refer to PHP manual for valid fetch modes. |
$rawSql | string | The raw SQL with parameter values inserted into the corresponding placeholders |
return | array | The cache key |
---|
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.
public string getRawSql ( ) | ||
return | string | The raw SQL with parameter values inserted into the corresponding placeholders in $sql. |
---|
Returns the SQL statement for this command.
public string getSql ( ) | ||
return | string | The SQL statement to be executed |
---|
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.
public $this insert ( $table, $columns ) | ||
$table | string | The table that new rows will be inserted into. |
$columns | array|yii\db\Query | The column data (name => value) to be inserted into the table or instance of \yii\db\yii\db\Query to perform INSERT INTO ... SELECT SQL statement. Passing of \yii\db\yii\db\Query is available since version 2.0.11. |
return | $this | The command object itself |
---|
Executes a prepared statement.
It's a wrapper around \PDOStatement::execute() to support transactions and retry handlers.
protected void internalExecute ( $rawSql ) | ||
$rawSql | string|null | The rawSql if it has been created. |
throws | yii\db\Exception | if execution failed. |
---|
Logs the current database query if query logging is enabled and returns the profiling token if profiling is enabled.
protected array logQuery ( $category ) | ||
$category | string | The log category. |
return | 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. |
---|
Disables query cache for this command.
public $this noCache ( ) | ||
return | $this | The command object itself |
---|
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.
public void prepare ( $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. |
throws | yii\db\Exception | if there is any DB error |
---|
Executes the SQL statement and returns query result.
This method is for executing a SQL query that returns result set, such as SELECT
.
public yii\db\DataReader query ( ) | ||
return | yii\db\DataReader | The reader object for fetching the query result |
---|---|---|
throws | yii\db\Exception | execution failed |
Executes the SQL statement and returns ALL rows at once.
public array queryAll ( $fetchMode = null ) | ||
$fetchMode | integer | The 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. |
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. |
---|---|---|
throws | yii\db\Exception | execution failed |
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.
public array queryColumn ( ) | ||
return | array | The first column of the query result. Empty array is returned if the query results in nothing. |
---|---|---|
throws | yii\db\Exception | execution failed |
Performs the actual DB query of a SQL statement.
protected mixed queryInternal ( $method, $fetchMode = null ) | ||
$method | string | Method of PDOStatement to be called |
$fetchMode | integer | The 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. |
return | mixed | The method execution result |
---|---|---|
throws | yii\db\Exception | if the query causes any problem |
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.
public array|false queryOne ( $fetchMode = null ) | ||
$fetchMode | integer | The 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. |
return | array|false | The first row (in terms of an array) of the query result. False is returned if the query results in nothing. |
---|---|---|
throws | yii\db\Exception | execution failed |
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.
public string|null|false queryScalar ( ) | ||
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. |
---|---|---|
throws | yii\db\Exception | execution failed |
Refreshes table schema, which was marked by requireTableSchemaRefresh().
protected void refreshTableSchema ( ) |
Creates a SQL command for renaming a column.
public $this renameColumn ( $table, $oldName, $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. |
return | $this | The command object itself |
---|
Creates a SQL command for renaming a DB table.
public $this renameTable ( $table, $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. |
return | $this | The command object itself |
---|
Marks a specified table schema to be refreshed after command execution.
protected $this requireTableSchemaRefresh ( $name ) | ||
$name | string | Name of the table, which schema should be refreshed. |
return | $this | This command instance |
---|
Marks the command to be executed in transaction.
protected $this requireTransaction ( $isolationLevel = null ) | ||
$isolationLevel | string|null | The isolation level to use for this transaction. See yii\db\Transaction::begin() for details. |
return | $this | This command instance. |
---|
Resets command properties to their initial state.
protected void reset ( ) |
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.
public $this resetSequence ( $table, $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 the maximum existing value +1. |
return | $this | The command object itself |
---|---|---|
throws | yii\base\NotSupportedException | if this is not supported by the underlying DBMS |
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.
See also:
public $this setRawSql ( $sql ) | ||
$sql | string | The SQL statement to be set. |
return | $this | This command instance |
---|
Sets a callable (e.g. anonymous function) that is called when yii\db\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 recieve a database exception thrown and a current attempt (to execute the command) number starting from 1.
protected $this setRetryHandler ( callable $handler ) | ||
$handler | callable | A PHP callback to handle database exceptions. |
return | $this | This command instance. |
---|
Specifies the SQL statement to be executed. The SQL statement will be quoted using yii\db\Connection::quoteSql().
The previous SQL (if any) will be discarded, and $params will be cleared as well. See reset() for details.
See also:
public $this setSql ( $sql ) | ||
$sql | string | The SQL statement to be set. |
return | $this | This command instance |
---|
Creates a SQL command for truncating a DB table.
public $this truncateTable ( $table ) | ||
$table | string | The table to be truncated. The name will be properly quoted by the method. |
return | $this | The command object itself |
---|
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.
public $this update ( $table, $columns, $condition = '', $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 yii\db\Query::where() on how to specify condition. |
$params | array | The parameters to be bound to the command |
return | $this | The command object itself |
---|
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' => 'http://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.
public $this upsert ( $table, $insertColumns, $updateColumns = true, $params = [] ) | ||
$table | string | The table that new rows will be inserted into/updated in. |
$insertColumns | array|yii\db\Query | The column data (name => value) to be inserted into the table or instance
of yii\db\Query to perform |
$updateColumns | array|boolean | The column data (name => value) to be updated if they already exist.
If |
$params | array | The parameters to be bound to the command. |
return | $this | The command object itself. |
---|