Command
extends Command
in package
Command represents an Oracle SQL statement to be executed against a database.
Tags
Table of Contents
Properties
- $behaviors : array<string|int, Behavior>
- $db : Connection
- $fetchMode : int
- $params : array<string|int, mixed>
- $pdoStatement : PDOStatement
- $queryCacheDependency : Dependency
- $queryCacheDuration : int
- $rawSql : string
- $sql : string
- $pendingParams : array<string|int, mixed>
- $_behaviors : array<string|int, Behavior>|null
- $_events : array<string|int, mixed>
- $_eventWildcards : array<string|int, mixed>
- $_isolationLevel : string|null|false
- $_refreshTableName : string
- $_retryHandler : callable
- $_sql : string
Methods
- __call() : mixed
- Calls the named method which is not a class method.
- __clone() : mixed
- This method is called after the object is created by cloning an existing one.
- __construct() : mixed
- Constructor.
- __get() : mixed
- Returns the value of a component property.
- __isset() : bool
- Checks if a property is set, i.e. defined and not null.
- __set() : mixed
- Sets the value of a component property.
- __unset() : mixed
- Sets a component property to be null.
- addCheck() : $this
- Creates a SQL command for adding a check constraint to an existing table.
- addColumn() : $this
- Creates a SQL command for adding a new DB column.
- addCommentOnColumn() : $this
- Builds a SQL command for adding comment to column.
- addCommentOnTable() : $this
- Builds a SQL command for adding comment to table.
- addDefaultValue() : $this
- Creates a SQL command for adding a default value constraint to an existing table.
- addForeignKey() : $this
- Creates a SQL command for adding a foreign key constraint to an existing table.
- addPrimaryKey() : $this
- Creates a SQL command for adding a primary key constraint to an existing table.
- addUnique() : $this
- Creates a SQL command for adding an unique constraint to an existing table.
- alterColumn() : $this
- Creates a SQL command for changing the definition of a column.
- attachBehavior() : Behavior
- Attaches a behavior to this component.
- attachBehaviors() : mixed
- Attaches a list of behaviors to the component.
- batchInsert() : $this
- Creates a batch INSERT command.
- behaviors() : array<string|int, mixed>
- Returns a list of behaviors that this component should behave as.
- bindParam() : $this
- Binds a parameter to the SQL statement to be executed.
- bindValue() : $this
- Binds a value to a parameter.
- bindValues() : $this
- Binds a list of values to the corresponding parameters.
- cache() : $this
- Enables query cache for this command.
- cancel() : mixed
- Cancels the execution of the SQL statement.
- canGetProperty() : bool
- Returns a value indicating whether a property can be read.
- canSetProperty() : bool
- Returns a value indicating whether a property can be set.
- checkIntegrity() : $this
- Builds a SQL command for enabling or disabling integrity check.
- className() : string
- Returns the fully qualified name of this class.
- createIndex() : $this
- Creates a SQL command for creating a new index.
- createTable() : $this
- Creates a SQL command for creating a new DB table.
- createView() : $this
- Creates a SQL View.
- delete() : $this
- Creates a DELETE command.
- detachBehavior() : Behavior|null
- Detaches a behavior from the component.
- detachBehaviors() : mixed
- Detaches all behaviors from the component.
- dropCheck() : $this
- Creates a SQL command for dropping a check constraint.
- dropColumn() : $this
- Creates a SQL command for dropping a DB column.
- dropCommentFromColumn() : $this
- Builds a SQL command for dropping comment from column.
- dropCommentFromTable() : $this
- Builds a SQL command for dropping comment from table.
- dropDefaultValue() : $this
- Creates a SQL command for dropping a default value constraint.
- dropForeignKey() : $this
- Creates a SQL command for dropping a foreign key constraint.
- dropIndex() : $this
- Creates a SQL command for dropping an index.
- dropPrimaryKey() : $this
- Creates a SQL command for removing a primary key constraint to an existing table.
- dropTable() : $this
- Creates a SQL command for dropping a DB table.
- dropUnique() : $this
- Creates a SQL command for dropping an unique constraint.
- dropView() : $this
- Drops a SQL View.
- ensureBehaviors() : mixed
- Makes sure that the behaviors declared in [[behaviors()]] are attached to this component.
- execute() : int
- Executes the SQL statement.
- executeResetSequence() : mixed
- Executes a db command resetting the sequence value of a table's primary key.
- getBehavior() : Behavior|null
- Returns the named behavior object.
- getBehaviors() : array<string|int, Behavior>
- Returns all behaviors attached to this component.
- 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.
- hasEventHandlers() : bool
- Returns a value indicating whether there is any handler attached to the named event.
- hasMethod() : bool
- Returns a value indicating whether a method is defined.
- hasProperty() : bool
- Returns a value indicating whether a property is defined for this component.
- init() : mixed
- Initializes the object.
- insert() : $this
- Creates an INSERT command.
- noCache() : $this
- Disables query cache for this command.
- off() : bool
- Detaches an existing event handler from this component.
- on() : mixed
- Attaches an event handler to an event.
- prepare() : mixed
- Prepares the SQL statement to be executed.
- query() : DataReader
- Executes the SQL statement and returns query result.
- queryAll() : array<string|int, mixed>
- Executes the SQL statement and returns ALL rows at once.
- queryColumn() : array<string|int, mixed>
- Executes the SQL statement and returns the first column of the result.
- queryOne() : array<string|int, mixed>|false
- Executes the SQL statement and returns the first row of the result.
- queryScalar() : string|int|null|false
- Executes the SQL statement and returns the value of the first column in the first row of data.
- renameColumn() : $this
- Creates a SQL command for renaming a column.
- renameTable() : $this
- Creates a SQL command for renaming a DB table.
- resetSequence() : $this
- Creates a SQL command for resetting the sequence value of a table's primary key.
- setRawSql() : $this
- Specifies the SQL statement to be executed. The SQL statement will not be modified in any way.
- setSql() : $this
- Specifies the SQL statement to be executed. The SQL statement will be quoted using [[Connection::quoteSql()]].
- trigger() : mixed
- Triggers an event.
- truncateTable() : $this
- Creates a SQL command for truncating a DB table.
- update() : $this
- Creates an UPDATE command.
- upsert() : $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.
- bindPendingParams() : mixed
- Binds pending parameters that were registered via [[bindValue()]] and [[bindValues()]].
- getCacheKey() : array<string|int, mixed>
- Returns the cache key for the query.
- internalExecute() : mixed
- Executes a prepared statement.
- logQuery() : array<string|int, mixed>
- Logs the current database query if query logging is enabled and returns the profiling token if profiling is enabled.
- queryInternal() : mixed
- Performs the actual DB query of a SQL statement.
- refreshTableSchema() : mixed
- Refreshes table schema, which was marked by [[requireTableSchemaRefresh()]].
- requireTableSchemaRefresh() : $this
- Marks a specified table schema to be refreshed after command execution.
- requireTransaction() : $this
- Marks the command to be executed in transaction.
- reset() : mixed
- Resets command properties to their initial state.
- setRetryHandler() : $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:
- attachBehaviorInternal() : Behavior
- Attaches a behavior to this component.
Properties
$behaviors read-only
public
array<string|int, Behavior>
$behaviors
List of behaviors attached to this component.
$db
public
Connection
$db
the DB connection that this command is associated with
$fetchMode
public
int
$fetchMode
= \PDO::FETCH_ASSOC
the default fetch mode for this command.
Tags
$params
public
array<string|int, mixed>
$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.
$pdoStatement
public
PDOStatement
$pdoStatement
the PDOStatement object that this command is associated with
$queryCacheDependency
public
Dependency
$queryCacheDependency
the dependency to be associated with the cached query result for this command
Tags
$queryCacheDuration
public
int
$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.
Tags
$rawSql
public
string
$rawSql
The raw SQL with parameter values inserted into the corresponding placeholders in [[sql]].
$sql
public
string
$sql
The SQL statement to be executed.
$pendingParams
protected
array<string|int, mixed>
$pendingParams
= []
pending parameters to be bound to the current PDO statement.
Tags
$_behaviors
private
array<string|int, Behavior>|null
$_behaviors
the attached behaviors (behavior name => behavior). This is null
when not initialized.
$_events
private
array<string|int, mixed>
$_events
= []
the attached event handlers (event name => handlers)
$_eventWildcards
private
array<string|int, mixed>
$_eventWildcards
= []
the event handlers attached for wildcard patterns (event name wildcard => handlers)
Tags
$_isolationLevel
private
string|null|false
$_isolationLevel
= false
the isolation level to use for this transaction. See [[Transaction::begin()]] for details.
$_refreshTableName
private
string
$_refreshTableName
name of the table, which schema, should be refreshed after command execution.
$_retryHandler
private
callable
$_retryHandler
a callable (e.g. anonymous function) that is called when [[\yii\db\Exception]] is thrown when executing the command.
$_sql
private
string
$_sql
the SQL statement that this command represents
Methods
__call()
Calls the named method which is not a class method.
public
__call(string $name, array<string|int, mixed> $params) : mixed
This method will check if any attached behavior has the named method and will execute it if available.
Do not call this method directly as it is a PHP magic method that will be implicitly called when an unknown method is being invoked.
Parameters
- $name : string
-
the method name
- $params : array<string|int, mixed>
-
method parameters
Tags
Return values
mixed —the method return value
__clone()
This method is called after the object is created by cloning an existing one.
public
__clone() : mixed
It removes all behaviors because they are attached to the old object.
__construct()
Constructor.
public
__construct([array<string|int, mixed> $config = [] ]) : mixed
The default implementation does two things:
- Initializes the object with the given configuration
$config
. - Call [[init()]].
If this method is overridden in a child class, it is recommended that
- the last parameter of the constructor is a configuration array, like
$config
here. - call the parent implementation at the end of the constructor.
Parameters
- $config : array<string|int, mixed> = []
-
name-value pairs that will be used to initialize the object properties
__get()
Returns the value of a component property.
public
__get(string $name) : mixed
This method will check in the following order and act accordingly:
- a property defined by a getter: return the getter result
- a property of a behavior: return the behavior property value
Do not call this method directly as it is a PHP magic method that
will be implicitly called when executing $value = $component->property;
.
Parameters
- $name : string
-
the property name
Tags
Return values
mixed —the property value or the value of a behavior's property
__isset()
Checks if a property is set, i.e. defined and not null.
public
__isset(string $name) : bool
This method will check in the following order and act accordingly:
- a property defined by a setter: return whether the property is set
- a property of a behavior: return whether the property is set
- return
false
for non existing properties
Do not call this method directly as it is a PHP magic method that
will be implicitly called when executing isset($component->property)
.
Parameters
- $name : string
-
the property name or the event name
Tags
Return values
bool —whether the named property is set
__set()
Sets the value of a component property.
public
__set(string $name, mixed $value) : mixed
This method will check in the following order and act accordingly:
- a property defined by a setter: set the property value
- an event in the format of "on xyz": attach the handler to the event "xyz"
- a behavior in the format of "as xyz": attach the behavior named as "xyz"
- a property of a behavior: set the behavior property value
Do not call this method directly as it is a PHP magic method that
will be implicitly called when executing $component->property = $value;
.
Parameters
- $name : string
-
the property name or the event name
- $value : mixed
-
the property value
Tags
__unset()
Sets a component property to be null.
public
__unset(string $name) : mixed
This method will check in the following order and act accordingly:
- a property defined by a setter: set the property value to be null
- a property of a behavior: set the property value to be null
Do not call this method directly as it is a PHP magic method that
will be implicitly called when executing unset($component->property)
.
Parameters
- $name : string
-
the property name
Tags
addCheck()
Creates a SQL command for adding a check constraint to an existing table.
public
addCheck(string $name, string $table, string $expression) : $this
Parameters
- $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
CHECK
constraint.
Tags
Return values
$this —the command object itself.
addColumn()
Creates a SQL command for adding a new DB column.
public
addColumn(string $table, string $column, string $type) : $this
Parameters
- $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 given column type to the physical one. For example,
string
will be converted asvarchar(255)
, andstring not null
becomesvarchar(255) not null
.
Return values
$this —the command object itself
addCommentOnColumn()
Builds a SQL command for adding comment to column.
public
addCommentOnColumn(string $table, string $column, string $comment) : $this
Parameters
- $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.
Tags
Return values
$this —the command object itself
addCommentOnTable()
Builds a SQL command for adding comment to table.
public
addCommentOnTable(string $table, string $comment) : $this
Parameters
- $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.
Tags
Return values
$this —the command object itself
addDefaultValue()
Creates a SQL command for adding a default value constraint to an existing table.
public
addDefaultValue(string $name, string $table, string $column, mixed $value) : $this
Parameters
- $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.
Tags
Return values
$this —the command object itself.
addForeignKey()
Creates a SQL command for adding a foreign key constraint to an existing table.
public
addForeignKey(string $name, string $table, string|array<string|int, mixed> $columns, string $refTable, string|array<string|int, mixed> $refColumns[, string|null $delete = null ][, string|null $update = null ]) : $this
The method will properly quote the table and column names.
Parameters
- $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<string|int, mixed>
-
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<string|int, mixed>
-
the name of the column that the foreign key references to. If there are multiple columns, separate them with commas.
- $delete : string|null = null
-
the ON DELETE option. Most DBMS support these options: RESTRICT, CASCADE, NO ACTION, SET DEFAULT, SET NULL
- $update : string|null = null
-
the ON UPDATE option. Most DBMS support these options: RESTRICT, CASCADE, NO ACTION, SET DEFAULT, SET NULL
Return values
$this —the command object itself
addPrimaryKey()
Creates a SQL command for adding a primary key constraint to an existing table.
public
addPrimaryKey(string $name, string $table, string|array<string|int, mixed> $columns) : $this
The method will properly quote the table and column names.
Parameters
- $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<string|int, mixed>
-
comma separated string or array of columns that the primary key will consist of.
Return values
$this —the command object itself.
addUnique()
Creates a SQL command for adding an unique constraint to an existing table.
public
addUnique(string $name, string $table, string|array<string|int, mixed> $columns) : $this
Parameters
- $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<string|int, mixed>
-
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.
Tags
Return values
$this —the command object itself.
alterColumn()
Creates a SQL command for changing the definition of a column.
public
alterColumn(string $table, string $column, string $type) : $this
Parameters
- $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 asvarchar(255)
, andstring not null
becomesvarchar(255) not null
.
Return values
$this —the command object itself
attachBehavior()
Attaches a behavior to this component.
public
attachBehavior(string $name, string|array<string|int, mixed>|Behavior $behavior) : Behavior
This method will create the behavior object based on the given configuration. After that, the behavior object will be attached to this component by calling the [[Behavior::attach()]] method.
Parameters
- $name : string
-
the name of the behavior.
- $behavior : string|array<string|int, mixed>|Behavior
-
the behavior configuration. This can be one of the following:
- a [[Behavior]] object
- a string specifying the behavior class
- an object configuration array that will be passed to [[Yii::createObject()]] to create the behavior object.
Tags
Return values
Behavior —the behavior object
attachBehaviors()
Attaches a list of behaviors to the component.
public
attachBehaviors(array<string|int, mixed> $behaviors) : mixed
Each behavior is indexed by its name and should be a [[Behavior]] object, a string specifying the behavior class, or an configuration array for creating the behavior.
Parameters
- $behaviors : array<string|int, mixed>
-
list of behaviors to be attached to the component
Tags
batchInsert()
Creates a batch INSERT command.
public
batchInsert(string $table, array<string|int, mixed> $columns, array<string|int, mixed>|Generator $rows) : $this
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
- $table : string
-
the table that new rows will be inserted into.
- $columns : array<string|int, mixed>
-
the column names
- $rows : array<string|int, mixed>|Generator
-
the rows to be batch inserted into the table
Return values
$this —the command object itself
behaviors()
Returns a list of behaviors that this component should behave as.
public
behaviors() : array<string|int, mixed>
Child classes may override this method to specify the behaviors they want to behave as.
The return value of this method should be an array of behavior objects or configurations indexed by behavior names. A behavior configuration can be either a string specifying the behavior class or an array of the following structure:
'behaviorName' => [
'class' => 'BehaviorClass',
'property1' => 'value1',
'property2' => 'value2',
]
Note that a behavior class must extend from [[Behavior]]. Behaviors can be attached using a name or anonymously. When a name is used as the array key, using this name, the behavior can later be retrieved using [[getBehavior()]] or be detached using [[detachBehavior()]]. Anonymous behaviors can not be retrieved or detached.
Behaviors declared in this method will be attached to the component automatically (on demand).
Return values
array<string|int, mixed> —the behavior configurations.
bindParam()
Binds a parameter to the SQL statement to be executed.
public
bindParam(string|int $name, mixed &$value[, int|null $dataType = null ][, int|null $length = null ][, mixed $driverOptions = null ]) : $this
Parameters
- $name : string|int
-
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 : int|null = null
-
SQL data type of the parameter. If null, the type is determined by the PHP type of the value.
- $length : int|null = null
-
length of the data type
- $driverOptions : mixed = null
-
the driver-specific options
Tags
Return values
$this —the current command being executed
bindValue()
Binds a value to a parameter.
public
bindValue(string|int $name, mixed $value[, int|null $dataType = null ]) : $this
Parameters
- $name : string|int
-
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 : int|null = null
-
SQL data type of the parameter. If null, the type is determined by the PHP type of the value.
Tags
Return values
$this —the current command being executed
bindValues()
Binds a list of values to the corresponding parameters.
public
bindValues(array<string|int, mixed> $values) : $this
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
- $values : array<string|int, mixed>
-
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 a [[yii\db\PdoValue]] class:new PdoValue(value, type)
, e.g.[':name' => 'John', ':profile' => new PdoValue($profile, \PDO::PARAM_LOB)]
.
Return values
$this —the current command being executed
cache()
Enables query cache for this command.
public
cache([int|null $duration = null ][, Dependency|null $dependency = null ]) : $this
Parameters
- $duration : int|null = null
-
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 : Dependency|null = null
-
the cache dependency associated with the cached query result.
Return values
$this —the command object itself
cancel()
Cancels the execution of the SQL statement.
public
cancel() : mixed
This method mainly sets [[pdoStatement]] to be null.
canGetProperty()
Returns a value indicating whether a property can be read.
public
canGetProperty(string $name[, bool $checkVars = true ][, bool $checkBehaviors = true ]) : bool
A property can be read if:
- the class has a getter method associated with the specified name (in this case, property name is case-insensitive);
- the class has a member variable with the specified name (when
$checkVars
is true); - an attached behavior has a readable property of the given name (when
$checkBehaviors
is true).
Parameters
- $name : string
-
the property name
- $checkVars : bool = true
-
whether to treat member variables as properties
- $checkBehaviors : bool = true
-
whether to treat behaviors' properties as properties of this component
Tags
Return values
bool —whether the property can be read
canSetProperty()
Returns a value indicating whether a property can be set.
public
canSetProperty(string $name[, bool $checkVars = true ][, bool $checkBehaviors = true ]) : bool
A property can be written if:
- the class has a setter method associated with the specified name (in this case, property name is case-insensitive);
- the class has a member variable with the specified name (when
$checkVars
is true); - an attached behavior has a writable property of the given name (when
$checkBehaviors
is true).
Parameters
- $name : string
-
the property name
- $checkVars : bool = true
-
whether to treat member variables as properties
- $checkBehaviors : bool = true
-
whether to treat behaviors' properties as properties of this component
Tags
Return values
bool —whether the property can be written
checkIntegrity()
Builds a SQL command for enabling or disabling integrity check.
public
checkIntegrity([bool $check = true ][, string $schema = '' ][, string $table = '' ]) : $this
Parameters
- $check : bool = true
-
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.
Tags
Return values
$this —the command object itself
className()
Returns the fully qualified name of this class.
public
static className() : string
Tags
Return values
string —the fully qualified name of this class.
createIndex()
Creates a SQL command for creating a new index.
public
createIndex(string $name, string $table, string|array<string|int, mixed> $columns[, bool $unique = false ]) : $this
Parameters
- $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<string|int, mixed>
-
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 : bool = false
-
whether to add UNIQUE constraint on the created index.
Return values
$this —the command object itself
createTable()
Creates a SQL command for creating a new DB table.
public
createTable(string $table, array<string|int, mixed> $columns[, string|null $options = null ]) : $this
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
- $table : string
-
the name of the table to be created. The name will be properly quoted by the method.
- $columns : array<string|int, mixed>
-
the columns (name => definition) in the new table.
- $options : string|null = null
-
additional SQL fragment that will be appended to the generated SQL.
Return values
$this —the command object itself
createView()
Creates a SQL View.
public
createView(string $viewName, string|Query $subquery) : $this
Parameters
- $viewName : string
-
the name of the view to be created.
- $subquery : string|Query
-
the select statement which defines the view. This can be either a string or a [[Query]] object.
Tags
Return values
$this —the command object itself.
delete()
Creates a DELETE command.
public
delete(string $table[, string|array<string|int, mixed> $condition = '' ][, array<string|int, mixed> $params = [] ]) : $this
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
- $table : string
-
the table where the data will be deleted from.
- $condition : string|array<string|int, mixed> = ''
-
the condition that will be put in the WHERE part. Please refer to [[Query::where()]] on how to specify condition.
- $params : array<string|int, mixed> = []
-
the parameters to be bound to the command
Return values
$this —the command object itself
detachBehavior()
Detaches a behavior from the component.
public
detachBehavior(string $name) : Behavior|null
The behavior's [[Behavior::detach()]] method will be invoked.
Parameters
- $name : string
-
the behavior's name.
Return values
Behavior|null —the detached behavior. Null if the behavior does not exist.
detachBehaviors()
Detaches all behaviors from the component.
public
detachBehaviors() : mixed
dropCheck()
Creates a SQL command for dropping a check constraint.
public
dropCheck(string $name, string $table) : $this
Parameters
- $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.
Tags
Return values
$this —the command object itself.
dropColumn()
Creates a SQL command for dropping a DB column.
public
dropColumn(string $table, string $column) : $this
Parameters
- $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 values
$this —the command object itself
dropCommentFromColumn()
Builds a SQL command for dropping comment from column.
public
dropCommentFromColumn(string $table, string $column) : $this
Parameters
- $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.
Tags
Return values
$this —the command object itself
dropCommentFromTable()
Builds a SQL command for dropping comment from table.
public
dropCommentFromTable(string $table) : $this
Parameters
- $table : string
-
the table whose column is to be commented. The table name will be properly quoted by the method.
Tags
Return values
$this —the command object itself
dropDefaultValue()
Creates a SQL command for dropping a default value constraint.
public
dropDefaultValue(string $name, string $table) : $this
Parameters
- $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.
Tags
Return values
$this —the command object itself.
dropForeignKey()
Creates a SQL command for dropping a foreign key constraint.
public
dropForeignKey(string $name, string $table) : $this
Parameters
- $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 values
$this —the command object itself
dropIndex()
Creates a SQL command for dropping an index.
public
dropIndex(string $name, string $table) : $this
Parameters
- $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 values
$this —the command object itself
dropPrimaryKey()
Creates a SQL command for removing a primary key constraint to an existing table.
public
dropPrimaryKey(string $name, string $table) : $this
Parameters
- $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 values
$this —the command object itself
dropTable()
Creates a SQL command for dropping a DB table.
public
dropTable(string $table) : $this
Parameters
- $table : string
-
the table to be dropped. The name will be properly quoted by the method.
Return values
$this —the command object itself
dropUnique()
Creates a SQL command for dropping an unique constraint.
public
dropUnique(string $name, string $table) : $this
Parameters
- $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.
Tags
Return values
$this —the command object itself.
dropView()
Drops a SQL View.
public
dropView(string $viewName) : $this
Parameters
- $viewName : string
-
the name of the view to be dropped.
Tags
Return values
$this —the command object itself.
ensureBehaviors()
Makes sure that the behaviors declared in [[behaviors()]] are attached to this component.
public
ensureBehaviors() : mixed
execute()
Executes the SQL statement.
public
execute() : int
This method should only be used for executing non-query SQL statement, such as INSERT
, DELETE
, UPDATE
SQLs.
No result set will be returned.
Tags
Return values
int —number of rows affected by the execution.
executeResetSequence()
Executes a db command resetting the sequence value of a table's primary key.
public
executeResetSequence(string $table[, mixed $value = null ]) : mixed
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
- $table : string
-
the name of the table whose primary key sequence is reset
- $value : mixed = null
-
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.
Tags
getBehavior()
Returns the named behavior object.
public
getBehavior(string $name) : Behavior|null
Parameters
- $name : string
-
the behavior name
Return values
Behavior|null —the behavior object, or null if the behavior does not exist
getBehaviors()
Returns all behaviors attached to this component.
public
getBehaviors() : array<string|int, Behavior>
Return values
array<string|int, Behavior> —list of behaviors attached to this component
getRawSql()
Returns the raw SQL by inserting parameter values into the corresponding placeholders in [[sql]].
public
getRawSql() : string
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.
Return values
string —the raw SQL with parameter values inserted into the corresponding placeholders in [[sql]].
getSql()
Returns the SQL statement for this command.
public
getSql() : string
Return values
string —the SQL statement to be executed
hasEventHandlers()
Returns a value indicating whether there is any handler attached to the named event.
public
hasEventHandlers(string $name) : bool
Parameters
- $name : string
-
the event name
Return values
bool —whether there is any handler attached to the event.
hasMethod()
Returns a value indicating whether a method is defined.
public
hasMethod(string $name[, bool $checkBehaviors = true ]) : bool
A method is defined if:
- the class has a method with the specified name
- an attached behavior has a method with the given name (when
$checkBehaviors
is true).
Parameters
- $name : string
-
the property name
- $checkBehaviors : bool = true
-
whether to treat behaviors' methods as methods of this component
Return values
bool —whether the method is defined
hasProperty()
Returns a value indicating whether a property is defined for this component.
public
hasProperty(string $name[, bool $checkVars = true ][, bool $checkBehaviors = true ]) : bool
A property is defined if:
- the class has a getter or setter method associated with the specified name (in this case, property name is case-insensitive);
- the class has a member variable with the specified name (when
$checkVars
is true); - an attached behavior has a property of the given name (when
$checkBehaviors
is true).
Parameters
- $name : string
-
the property name
- $checkVars : bool = true
-
whether to treat member variables as properties
- $checkBehaviors : bool = true
-
whether to treat behaviors' properties as properties of this component
Tags
Return values
bool —whether the property is defined
init()
Initializes the object.
public
init() : mixed
This method is invoked at the end of the constructor after the object is initialized with the given configuration.
insert()
Creates an INSERT command.
public
insert(string $table, array<string|int, mixed>|Query $columns) : $this
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
- $table : string
-
the table that new rows will be inserted into.
- $columns : array<string|int, mixed>|Query
-
the column data (name => value) to be inserted into the table or instance of [[yii\db\Query|Query]] to perform INSERT INTO ... SELECT SQL statement. Passing of [[yii\db\Query|Query]] is available since version 2.0.11.
Return values
$this —the command object itself
noCache()
Disables query cache for this command.
public
noCache() : $this
Return values
$this —the command object itself
off()
Detaches an existing event handler from this component.
public
off(string $name[, callable|null $handler = null ]) : bool
This method is the opposite of [[on()]].
Note: in case wildcard pattern is passed for event name, only the handlers registered with this wildcard will be removed, while handlers registered with plain names matching this wildcard will remain.
Parameters
- $name : string
-
event name
- $handler : callable|null = null
-
the event handler to be removed. If it is null, all handlers attached to the named event will be removed.
Tags
Return values
bool —if a handler is found and detached
on()
Attaches an event handler to an event.
public
on(string $name, callable $handler[, mixed $data = null ][, bool $append = true ]) : mixed
The event handler must be a valid PHP callback. The following are some examples:
function ($event) { ... } // anonymous function
[$object, 'handleClick'] // $object->handleClick()
['Page', 'handleClick'] // Page::handleClick()
'handleClick' // global function handleClick()
The event handler must be defined with the following signature,
function ($event)
where $event
is an [[Event]] object which includes parameters associated with the event.
Since 2.0.14 you can specify event name as a wildcard pattern:
$component->on('event.group.*', function ($event) {
Yii::trace($event->name . ' is triggered.');
});
Parameters
- $name : string
-
the event name
- $handler : callable
-
the event handler
- $data : mixed = null
-
the data to be passed to the event handler when the event is triggered. When the event handler is invoked, this data can be accessed via [[Event::data]].
- $append : bool = true
-
whether to append new event handler to the end of the existing handler list. If false, the new handler will be inserted at the beginning of the existing handler list.
Tags
prepare()
Prepares the SQL statement to be executed.
public
prepare([bool|null $forRead = null ]) : mixed
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
- $forRead : bool|null = null
-
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.
Tags
query()
Executes the SQL statement and returns query result.
public
query() : DataReader
This method is for executing a SQL query that returns result set, such as SELECT
.
Tags
Return values
DataReader —the reader object for fetching the query result
queryAll()
Executes the SQL statement and returns ALL rows at once.
public
queryAll([int|null $fetchMode = null ]) : array<string|int, mixed>
Parameters
- $fetchMode : int|null = null
-
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.
Tags
Return values
array<string|int, mixed> —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()
Executes the SQL statement and returns the first column of the result.
public
queryColumn() : array<string|int, mixed>
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.
Tags
Return values
array<string|int, mixed> —the first column of the query result. Empty array is returned if the query results in nothing.
queryOne()
Executes the SQL statement and returns the first row of the result.
public
queryOne([int|null $fetchMode = null ]) : array<string|int, mixed>|false
This method is best used when only the first row of result is needed for a query.
Parameters
- $fetchMode : int|null = null
-
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.
Tags
Return values
array<string|int, mixed>|false —the first row (in terms of an array) of the query result. False is returned if the query results in nothing.
queryScalar()
Executes the SQL statement and returns the value of the first column in the first row of data.
public
queryScalar() : string|int|null|false
This method is best used when only a single value is needed for a query.
Tags
Return values
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.
renameColumn()
Creates a SQL command for renaming a column.
public
renameColumn(string $table, string $oldName, string $newName) : $this
Parameters
- $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 values
$this —the command object itself
renameTable()
Creates a SQL command for renaming a DB table.
public
renameTable(string $table, string $newName) : $this
Parameters
- $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 values
$this —the command object itself
resetSequence()
Creates a SQL command for resetting the sequence value of a table's primary key.
public
resetSequence(string $table[, mixed $value = null ]) : $this
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
- $table : string
-
the name of the table whose primary key sequence will be reset
- $value : mixed = null
-
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.
Tags
Return values
$this —the command object itself
setRawSql()
Specifies the SQL statement to be executed. The SQL statement will not be modified in any way.
public
setRawSql(string $sql) : $this
The previous SQL (if any) will be discarded, and [[params]] will be cleared as well. See [[reset()]] for details.
Parameters
- $sql : string
-
the SQL statement to be set.
Tags
Return values
$this —this command instance
setSql()
Specifies the SQL statement to be executed. The SQL statement will be quoted using [[Connection::quoteSql()]].
public
setSql(string $sql) : $this
The previous SQL (if any) will be discarded, and [[params]] will be cleared as well. See [[reset()]] for details.
Parameters
- $sql : string
-
the SQL statement to be set.
Tags
Return values
$this —this command instance
trigger()
Triggers an event.
public
trigger(string $name[, Event|null $event = null ]) : mixed
This method represents the happening of an event. It invokes all attached handlers for the event including class-level handlers.
Parameters
- $name : string
-
the event name
- $event : Event|null = null
-
the event instance. If not set, a default [[Event]] object will be created.
truncateTable()
Creates a SQL command for truncating a DB table.
public
truncateTable(string $table) : $this
Parameters
- $table : string
-
the table to be truncated. The name will be properly quoted by the method.
Return values
$this —the command object itself
update()
Creates an UPDATE command.
public
update(string $table, array<string|int, mixed> $columns[, string|array<string|int, mixed> $condition = '' ][, array<string|int, mixed> $params = [] ]) : $this
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
- $table : string
-
the table to be updated.
- $columns : array<string|int, mixed>
-
the column data (name => value) to be updated.
- $condition : string|array<string|int, mixed> = ''
-
the condition that will be put in the WHERE part. Please refer to [[Query::where()]] on how to specify condition.
- $params : array<string|int, mixed> = []
-
the parameters to be bound to the command
Return values
$this —the command object itself
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.
public
upsert(string $table, array<string|int, mixed>|Query $insertColumns[, array<string|int, mixed>|bool $updateColumns = true ][, array<string|int, mixed> $params = [] ]) : $this
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
- $table : string
-
the table that new rows will be inserted into/updated in.
- $insertColumns : array<string|int, mixed>|Query
-
the column data (name => value) to be inserted into the table or instance of [[Query]] to perform
INSERT INTO ... SELECT
SQL statement. - $updateColumns : array<string|int, mixed>|bool = true
-
the 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. Iffalse
is passed, no update will be performed if the column data already exists. - $params : array<string|int, mixed> = []
-
the parameters to be bound to the command.
Tags
Return values
$this —the command object itself.
bindPendingParams()
Binds pending parameters that were registered via [[bindValue()]] and [[bindValues()]].
protected
bindPendingParams() : mixed
getCacheKey()
Returns the cache key for the query.
protected
getCacheKey(string $method, int $fetchMode, mixed $rawSql) : array<string|int, mixed>
Parameters
- $method : string
-
method of PDOStatement to be called
- $fetchMode : int
-
the result fetch mode. Please refer to PHP manual for valid fetch modes.
- $rawSql : mixed
Tags
Return values
array<string|int, mixed> —the cache key
internalExecute()
Executes a prepared statement.
protected
internalExecute(string|null $rawSql) : mixed
It's a wrapper around [[\PDOStatement::execute()]] to support transactions and retry handlers.
Parameters
- $rawSql : string|null
-
the rawSql if it has been created.
Tags
logQuery()
Logs the current database query if query logging is enabled and returns the profiling token if profiling is enabled.
protected
logQuery(string $category) : array<string|int, mixed>
Parameters
- $category : string
-
the log category.
Return values
array<string|int, mixed> —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.
queryInternal()
Performs the actual DB query of a SQL statement.
protected
queryInternal(string $method[, int|null $fetchMode = null ]) : mixed
Parameters
- $method : string
-
method of PDOStatement to be called
- $fetchMode : int|null = null
-
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.
Tags
Return values
mixed —the method execution result
refreshTableSchema()
Refreshes table schema, which was marked by [[requireTableSchemaRefresh()]].
protected
refreshTableSchema() : mixed
Tags
requireTableSchemaRefresh()
Marks a specified table schema to be refreshed after command execution.
protected
requireTableSchemaRefresh(string $name) : $this
Parameters
- $name : string
-
name of the table, which schema should be refreshed.
Tags
Return values
$this —this command instance
requireTransaction()
Marks the command to be executed in transaction.
protected
requireTransaction([string|null $isolationLevel = null ]) : $this
Parameters
- $isolationLevel : string|null = null
-
The isolation level to use for this transaction. See [[Transaction::begin()]] for details.
Tags
Return values
$this —this command instance.
reset()
Resets command properties to their initial state.
protected
reset() : mixed
Tags
setRetryHandler()
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:
protected
setRetryHandler(callable $handler) : $this
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.
Parameters
- $handler : callable
-
a PHP callback to handle database exceptions.
Tags
Return values
$this —this command instance.
attachBehaviorInternal()
Attaches a behavior to this component.
private
attachBehaviorInternal(string|int $name, string|array<string|int, mixed>|Behavior $behavior) : Behavior
Parameters
- $name : string|int
-
the name of the behavior. If this is an integer, it means the behavior is an anonymous one. Otherwise, the behavior is a named one and any existing behavior with the same name will be detached first.
- $behavior : string|array<string|int, mixed>|Behavior
-
the behavior to be attached
Return values
Behavior —the attached behavior.