Class yii\db\Command
Inheritance | yii\db\Command » yii\base\Component » yii\base\BaseObject |
---|---|
Implements | yii\base\Configurable |
Subclasses | yii\db\oci\Command, yii\db\sqlite\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 |
$pendingParams | array | Pending parameters to be bound to the current PDO statement. | 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 raw SQL with parameter values inserted into the corresponding placeholders in $sql. | 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 https://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
Pending parameters to be bound to the current PDO statement.
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 raw SQL with parameter values inserted into the corresponding placeholders in $sql.
Method Details
Defined in: yii\base\Component::__call()
Calls the named method which is not a class method.
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.
public mixed __call ( $name, $params ) | ||
$name | string |
The method name |
$params | array |
Method parameters |
return | mixed |
The method return value |
---|---|---|
throws | yii\base\UnknownMethodException |
when calling unknown method |
public function __call($name, $params)
{
$this->ensureBehaviors();
foreach ($this->_behaviors as $object) {
if ($object->hasMethod($name)) {
return call_user_func_array([$object, $name], $params);
}
}
throw new UnknownMethodException('Calling unknown method: ' . get_class($this) . "::$name()");
}
Defined in: yii\base\Component::__clone()
This method is called after the object is created by cloning an existing one.
It removes all behaviors because they are attached to the old object.
public void __clone ( ) |
public function __clone()
{
$this->_events = [];
$this->_eventWildcards = [];
$this->_behaviors = null;
}
Defined in: yii\base\BaseObject::__construct()
Constructor.
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.
public void __construct ( $config = [] ) | ||
$config | array |
Name-value pairs that will be used to initialize the object properties |
public function __construct($config = [])
{
if (!empty($config)) {
Yii::configure($this, $config);
}
$this->init();
}
Defined in: yii\base\Component::__get()
Returns the value of a component property.
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;
.
See also __set().
public mixed __get ( $name ) | ||
$name | string |
The property name |
return | mixed |
The property value or the value of a behavior's property |
---|---|---|
throws | yii\base\UnknownPropertyException |
if the property is not defined |
throws | yii\base\InvalidCallException |
if the property is write-only. |
public function __get($name)
{
$getter = 'get' . $name;
if (method_exists($this, $getter)) {
// read property, e.g. getName()
return $this->$getter();
}
// behavior property
$this->ensureBehaviors();
foreach ($this->_behaviors as $behavior) {
if ($behavior->canGetProperty($name)) {
return $behavior->$name;
}
}
if (method_exists($this, 'set' . $name)) {
throw new InvalidCallException('Getting write-only property: ' . get_class($this) . '::' . $name);
}
throw new UnknownPropertyException('Getting unknown property: ' . get_class($this) . '::' . $name);
}
Defined in: yii\base\Component::__isset()
Checks if a property is set, i.e. defined and not null.
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)
.
public boolean __isset ( $name ) | ||
$name | string |
The property name or the event name |
return | boolean |
Whether the named property is set |
---|
public function __isset($name)
{
$getter = 'get' . $name;
if (method_exists($this, $getter)) {
return $this->$getter() !== null;
}
// behavior property
$this->ensureBehaviors();
foreach ($this->_behaviors as $behavior) {
if ($behavior->canGetProperty($name)) {
return $behavior->$name !== null;
}
}
return false;
}
Defined in: yii\base\Component::__set()
Sets the value of a component property.
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;
.
See also __get().
public void __set ( $name, $value ) | ||
$name | string |
The property name or the event name |
$value | mixed |
The property value |
throws | yii\base\UnknownPropertyException |
if the property is not defined |
---|---|---|
throws | yii\base\InvalidCallException |
if the property is read-only. |
public function __set($name, $value)
{
$setter = 'set' . $name;
if (method_exists($this, $setter)) {
// set property
$this->$setter($value);
return;
} elseif (strncmp($name, 'on ', 3) === 0) {
// on event: attach event handler
$this->on(trim(substr($name, 3)), $value);
return;
} elseif (strncmp($name, 'as ', 3) === 0) {
// as behavior: attach behavior
$name = trim(substr($name, 3));
$this->attachBehavior($name, $value instanceof Behavior ? $value : Yii::createObject($value));
return;
}
// behavior property
$this->ensureBehaviors();
foreach ($this->_behaviors as $behavior) {
if ($behavior->canSetProperty($name)) {
$behavior->$name = $value;
return;
}
}
if (method_exists($this, 'get' . $name)) {
throw new InvalidCallException('Setting read-only property: ' . get_class($this) . '::' . $name);
}
throw new UnknownPropertyException('Setting unknown property: ' . get_class($this) . '::' . $name);
}
Defined in: yii\base\Component::__unset()
Sets a component property to be null.
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)
.
public void __unset ( $name ) | ||
$name | string |
The property name |
throws | yii\base\InvalidCallException |
if the property is read only. |
---|
public function __unset($name)
{
$setter = 'set' . $name;
if (method_exists($this, $setter)) {
$this->$setter(null);
return;
}
// behavior property
$this->ensureBehaviors();
foreach ($this->_behaviors as $behavior) {
if ($behavior->canSetProperty($name)) {
$behavior->$name = null;
return;
}
}
throw new InvalidCallException('Unsetting an unknown or read-only property: ' . get_class($this) . '::' . $name);
}
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. |
---|
public function addCheck($name, $table, $expression)
{
$sql = $this->db->getQueryBuilder()->addCheck($name, $table, $expression);
return $this->setSql($sql)->requireTableSchemaRefresh($table);
}
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 given column type to the physical one. For example, |
return | $this |
The command object itself |
---|
public function addColumn($table, $column, $type)
{
$sql = $this->db->getQueryBuilder()->addColumn($table, $column, $type);
return $this->setSql($sql)->requireTableSchemaRefresh($table);
}
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 |
---|
public function addCommentOnColumn($table, $column, $comment)
{
$sql = $this->db->getQueryBuilder()->addCommentOnColumn($table, $column, $comment);
return $this->setSql($sql)->requireTableSchemaRefresh($table);
}
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 |
---|
public function addCommentOnTable($table, $comment)
{
$sql = $this->db->getQueryBuilder()->addCommentOnTable($table, $comment);
return $this->setSql($sql);
}
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. |
---|
public function addDefaultValue($name, $table, $column, $value)
{
$sql = $this->db->getQueryBuilder()->addDefaultValue($name, $table, $column, $value);
return $this->setSql($sql)->requireTableSchemaRefresh($table);
}
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|null |
The ON DELETE option. Most DBMS support these options: RESTRICT, CASCADE, NO ACTION, SET DEFAULT, SET NULL |
$update | string|null |
The ON UPDATE option. Most DBMS support these options: RESTRICT, CASCADE, NO ACTION, SET DEFAULT, SET NULL |
return | $this |
The command object itself |
---|
public function addForeignKey($name, $table, $columns, $refTable, $refColumns, $delete = null, $update = null)
{
$sql = $this->db->getQueryBuilder()->addForeignKey($name, $table, $columns, $refTable, $refColumns, $delete, $update);
return $this->setSql($sql)->requireTableSchemaRefresh($table);
}
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. |
---|
public function addPrimaryKey($name, $table, $columns)
{
$sql = $this->db->getQueryBuilder()->addPrimaryKey($name, $table, $columns);
return $this->setSql($sql)->requireTableSchemaRefresh($table);
}
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. |
---|
public function addUnique($name, $table, $columns)
{
$sql = $this->db->getQueryBuilder()->addUnique($name, $table, $columns);
return $this->setSql($sql)->requireTableSchemaRefresh($table);
}
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 |
---|
public function alterColumn($table, $column, $type)
{
$sql = $this->db->getQueryBuilder()->alterColumn($table, $column, $type);
return $this->setSql($sql)->requireTableSchemaRefresh($table);
}
Defined in: yii\base\Component::attachBehavior()
Attaches a behavior to this component.
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 yii\base\Behavior::attach() method.
See also detachBehavior().
public yii\base\Behavior attachBehavior ( $name, $behavior ) | ||
$name | string |
The name of the behavior. |
$behavior | string|array|yii\base\Behavior |
The behavior configuration. This can be one of the following:
|
return | yii\base\Behavior |
The behavior object |
---|
public function attachBehavior($name, $behavior)
{
$this->ensureBehaviors();
return $this->attachBehaviorInternal($name, $behavior);
}
Defined in: yii\base\Component::attachBehaviors()
Attaches a list of behaviors to the component.
Each behavior is indexed by its name and should be a yii\base\Behavior object, a string specifying the behavior class, or an configuration array for creating the behavior.
See also attachBehavior().
public void attachBehaviors ( $behaviors ) | ||
$behaviors | array |
List of behaviors to be attached to the component |
public function attachBehaviors($behaviors)
{
$this->ensureBehaviors();
foreach ($behaviors as $name => $behavior) {
$this->attachBehaviorInternal($name, $behavior);
}
}
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 |
---|
public function batchInsert($table, $columns, $rows)
{
$table = $this->db->quoteSql($table);
$columns = array_map(function ($column) {
return $this->db->quoteSql($column);
}, $columns);
$params = [];
$sql = $this->db->getQueryBuilder()->batchInsert($table, $columns, $rows, $params);
$this->setRawSql($sql);
$this->bindValues($params);
return $this;
}
Defined in: yii\base\Component::behaviors()
Returns a list of behaviors that this component should behave as.
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 yii\base\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).
public array behaviors ( ) | ||
return | array |
The behavior configurations. |
---|
public function behaviors()
{
return [];
}
Binds a parameter to the SQL statement to be executed.
See also https://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|null |
SQL data type of the parameter. If null, the type is determined by the PHP type of the value. |
$length | integer|null |
Length of the data type |
$driverOptions | mixed |
The driver-specific options |
return | $this |
The current command being executed |
---|
public function bindParam($name, &$value, $dataType = null, $length = null, $driverOptions = null)
{
$this->prepare();
if ($dataType === null) {
$dataType = $this->db->getSchema()->getPdoType($value);
}
if ($length === null) {
$this->pdoStatement->bindParam($name, $value, $dataType);
} elseif ($driverOptions === null) {
$this->pdoStatement->bindParam($name, $value, $dataType, $length);
} else {
$this->pdoStatement->bindParam($name, $value, $dataType, $length, $driverOptions);
}
$this->params[$name] = &$value;
return $this;
}
Binds pending parameters that were registered via bindValue() and bindValues().
Note that this method requires an active $pdoStatement.
protected void bindPendingParams ( ) |
protected function bindPendingParams()
{
foreach ($this->pendingParams as $name => $value) {
$this->pdoStatement->bindValue($name, $value[0], $value[1]);
}
$this->pendingParams = [];
}
Binds a value to a parameter.
See also https://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|null |
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 |
---|
public function bindValue($name, $value, $dataType = null)
{
if ($dataType === null) {
$dataType = $this->db->getSchema()->getPdoType($value);
}
$this->pendingParams[$name] = [$value, $dataType];
$this->params[$name] = $value;
return $this;
}
Binds a list of values to the corresponding parameters.
This is similar to bindValue() except that it binds multiple values at a time. Note that the SQL data type of each value is determined by its PHP type.
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 |
---|
public function bindValues($values)
{
if (empty($values)) {
return $this;
}
$schema = $this->db->getSchema();
foreach ($values as $name => $value) {
if (is_array($value)) { // TODO: Drop in Yii 2.1
$this->pendingParams[$name] = $value;
$this->params[$name] = $value[0];
} elseif ($value instanceof PdoValue) {
$this->pendingParams[$name] = [$value->getValue(), $value->getType()];
$this->params[$name] = $value->getValue();
} else {
if (version_compare(PHP_VERSION, '8.1.0') >= 0) {
if ($value instanceof \BackedEnum) {
$value = $value->value;
} elseif ($value instanceof \UnitEnum) {
$value = $value->name;
}
}
$type = $schema->getPdoType($value);
$this->pendingParams[$name] = [$value, $type];
$this->params[$name] = $value;
}
}
return $this;
}
Enables query cache for this command.
public $this cache ( $duration = null, $dependency = null ) | ||
$duration | integer|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 yii\db\Connection::$queryCacheDuration will be used instead. Use 0 to indicate that the cached data will never expire. |
$dependency | yii\caching\Dependency|null |
The cache dependency associated with the cached query result. |
return | $this |
The command object itself |
---|
public function cache($duration = null, $dependency = null)
{
$this->queryCacheDuration = $duration === null ? $this->db->queryCacheDuration : $duration;
$this->queryCacheDependency = $dependency;
return $this;
}
Defined in: yii\base\Component::canGetProperty()
Returns a value indicating whether a property can be read.
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).
See also canSetProperty().
public boolean canGetProperty ( $name, $checkVars = true, $checkBehaviors = true ) | ||
$name | string |
The property name |
$checkVars | boolean |
Whether to treat member variables as properties |
$checkBehaviors | boolean |
Whether to treat behaviors' properties as properties of this component |
return | boolean |
Whether the property can be read |
---|
public function canGetProperty($name, $checkVars = true, $checkBehaviors = true)
{
if (method_exists($this, 'get' . $name) || $checkVars && property_exists($this, $name)) {
return true;
} elseif ($checkBehaviors) {
$this->ensureBehaviors();
foreach ($this->_behaviors as $behavior) {
if ($behavior->canGetProperty($name, $checkVars)) {
return true;
}
}
}
return false;
}
Defined in: yii\base\Component::canSetProperty()
Returns a value indicating whether a property can be set.
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).
See also canGetProperty().
public boolean canSetProperty ( $name, $checkVars = true, $checkBehaviors = true ) | ||
$name | string |
The property name |
$checkVars | boolean |
Whether to treat member variables as properties |
$checkBehaviors | boolean |
Whether to treat behaviors' properties as properties of this component |
return | boolean |
Whether the property can be written |
---|
public function canSetProperty($name, $checkVars = true, $checkBehaviors = true)
{
if (method_exists($this, 'set' . $name) || $checkVars && property_exists($this, $name)) {
return true;
} elseif ($checkBehaviors) {
$this->ensureBehaviors();
foreach ($this->_behaviors as $behavior) {
if ($behavior->canSetProperty($name, $checkVars)) {
return true;
}
}
}
return false;
}
Cancels the execution of the SQL statement.
This method mainly sets $pdoStatement to be null.
public void cancel ( ) |
public function cancel()
{
$this->pdoStatement = null;
}
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 |
public function checkIntegrity($check = true, $schema = '', $table = '')
{
$sql = $this->db->getQueryBuilder()->checkIntegrity($check, $schema, $table);
return $this->setSql($sql);
}
::class
instead.
Defined in: yii\base\BaseObject::className()
Returns the fully qualified name of this class.
public static string className ( ) | ||
return | string |
The fully qualified name of this class. |
---|
public static function className()
{
return get_called_class();
}
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 |
---|
public function createIndex($name, $table, $columns, $unique = false)
{
$sql = $this->db->getQueryBuilder()->createIndex($name, $table, $columns, $unique);
return $this->setSql($sql)->requireTableSchemaRefresh($table);
}
Creates a SQL command for creating a new DB table.
The columns in the new table should be specified as name-definition pairs (e.g. 'name' => 'string'), where name stands for a column name which will be properly quoted by the method, and definition stands for the column type which must contain an abstract DB type.
The method 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.
Example usage:
`
php
Yii::$app->db->createCommand()->createTable('post', [
'id' => 'pk',
'title' => 'string',
'text' => 'text',
'column_name double precision null default null',
]);
`
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|null |
Additional SQL fragment that will be appended to the generated SQL. |
return | $this |
The command object itself |
---|
public function createTable($table, $columns, $options = null)
{
$sql = $this->db->getQueryBuilder()->createTable($table, $columns, $options);
return $this->setSql($sql)->requireTableSchemaRefresh($table);
}
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. |
---|
public function createView($viewName, $subquery)
{
$sql = $this->db->getQueryBuilder()->createView($viewName, $subquery);
return $this->setSql($sql)->requireTableSchemaRefresh($viewName);
}
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 |
---|
public function delete($table, $condition = '', $params = [])
{
$sql = $this->db->getQueryBuilder()->delete($table, $condition, $params);
return $this->setSql($sql)->bindValues($params);
}
Defined in: yii\base\Component::detachBehavior()
Detaches a behavior from the component.
The behavior's yii\base\Behavior::detach() method will be invoked.
public yii\base\Behavior|null detachBehavior ( $name ) | ||
$name | string |
The behavior's name. |
return | yii\base\Behavior|null |
The detached behavior. Null if the behavior does not exist. |
---|
public function detachBehavior($name)
{
$this->ensureBehaviors();
if (isset($this->_behaviors[$name])) {
$behavior = $this->_behaviors[$name];
unset($this->_behaviors[$name]);
$behavior->detach();
return $behavior;
}
return null;
}
Defined in: yii\base\Component::detachBehaviors()
Detaches all behaviors from the component.
public void detachBehaviors ( ) |
public function detachBehaviors()
{
$this->ensureBehaviors();
foreach ($this->_behaviors as $name => $behavior) {
$this->detachBehavior($name);
}
}
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. |
---|
public function dropCheck($name, $table)
{
$sql = $this->db->getQueryBuilder()->dropCheck($name, $table);
return $this->setSql($sql)->requireTableSchemaRefresh($table);
}
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 |
---|
public function dropColumn($table, $column)
{
$sql = $this->db->getQueryBuilder()->dropColumn($table, $column);
return $this->setSql($sql)->requireTableSchemaRefresh($table);
}
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 |
---|
public function dropCommentFromColumn($table, $column)
{
$sql = $this->db->getQueryBuilder()->dropCommentFromColumn($table, $column);
return $this->setSql($sql)->requireTableSchemaRefresh($table);
}
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 |
---|
public function dropCommentFromTable($table)
{
$sql = $this->db->getQueryBuilder()->dropCommentFromTable($table);
return $this->setSql($sql);
}
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. |
---|
public function dropDefaultValue($name, $table)
{
$sql = $this->db->getQueryBuilder()->dropDefaultValue($name, $table);
return $this->setSql($sql)->requireTableSchemaRefresh($table);
}
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 |
---|
public function dropForeignKey($name, $table)
{
$sql = $this->db->getQueryBuilder()->dropForeignKey($name, $table);
return $this->setSql($sql)->requireTableSchemaRefresh($table);
}
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 |
---|
public function dropIndex($name, $table)
{
$sql = $this->db->getQueryBuilder()->dropIndex($name, $table);
return $this->setSql($sql)->requireTableSchemaRefresh($table);
}
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 |
---|
public function dropPrimaryKey($name, $table)
{
$sql = $this->db->getQueryBuilder()->dropPrimaryKey($name, $table);
return $this->setSql($sql)->requireTableSchemaRefresh($table);
}
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 |
---|
public function dropTable($table)
{
$sql = $this->db->getQueryBuilder()->dropTable($table);
return $this->setSql($sql)->requireTableSchemaRefresh($table);
}
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. |
---|
public function dropUnique($name, $table)
{
$sql = $this->db->getQueryBuilder()->dropUnique($name, $table);
return $this->setSql($sql)->requireTableSchemaRefresh($table);
}
Drops a SQL View.
public $this dropView ( $viewName ) | ||
$viewName | string |
The name of the view to be dropped. |
return | $this |
The command object itself. |
---|
public function dropView($viewName)
{
$sql = $this->db->getQueryBuilder()->dropView($viewName);
return $this->setSql($sql)->requireTableSchemaRefresh($viewName);
}
Defined in: yii\base\Component::ensureBehaviors()
Makes sure that the behaviors declared in behaviors() are attached to this component.
public void ensureBehaviors ( ) |
public function ensureBehaviors()
{
if ($this->_behaviors === null) {
$this->_behaviors = [];
foreach ($this->behaviors() as $name => $behavior) {
$this->attachBehaviorInternal($name, $behavior);
}
}
}
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 |
public function execute()
{
$sql = $this->getSql();
list($profile, $rawSql) = $this->logQuery(__METHOD__);
if ($sql == '') {
return 0;
}
$this->prepare(false);
try {
$profile and Yii::beginProfile($rawSql, __METHOD__);
$this->internalExecute($rawSql);
$n = $this->pdoStatement->rowCount();
$profile and Yii::endProfile($rawSql, __METHOD__);
$this->refreshTableSchema();
return $n;
} catch (Exception $e) {
$profile and Yii::endProfile($rawSql, __METHOD__);
throw $e;
}
}
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 |
---|
public function executeResetSequence($table, $value = null)
{
return $this->db->getQueryBuilder()->executeResetSequence($table, $value);
}
Defined in: yii\base\Component::getBehavior()
Returns the named behavior object.
public yii\base\Behavior|null getBehavior ( $name ) | ||
$name | string |
The behavior name |
return | yii\base\Behavior|null |
The behavior object, or null if the behavior does not exist |
---|
public function getBehavior($name)
{
$this->ensureBehaviors();
return isset($this->_behaviors[$name]) ? $this->_behaviors[$name] : null;
}
Defined in: yii\base\Component::getBehaviors()
Returns all behaviors attached to this component.
public yii\base\Behavior[] getBehaviors ( ) | ||
return | yii\base\Behavior[] |
List of behaviors attached to this component |
---|
public function getBehaviors()
{
$this->ensureBehaviors();
return $this->_behaviors;
}
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 | ||
return | array |
The cache key |
---|
protected function getCacheKey($method, $fetchMode, $rawSql)
{
$params = $this->params;
ksort($params);
return [
__CLASS__,
$method,
$fetchMode,
$this->db->dsn,
$this->db->username,
$this->getSql(),
json_encode($params),
];
}
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. |
---|
public function getRawSql()
{
if (empty($this->params)) {
return $this->_sql;
}
$params = [];
foreach ($this->params as $name => $value) {
if (is_string($name) && strncmp(':', $name, 1)) {
$name = ':' . $name;
}
if (is_string($value) || $value instanceof Expression) {
$params[$name] = $this->db->quoteValue((string)$value);
} elseif (is_bool($value)) {
$params[$name] = ($value ? 'TRUE' : 'FALSE');
} elseif ($value === null) {
$params[$name] = 'NULL';
} elseif (!is_object($value) && !is_resource($value)) {
$params[$name] = $value;
}
}
if (!isset($params[1])) {
return preg_replace_callback('#(:\w+)#', function ($matches) use ($params) {
$m = $matches[1];
return isset($params[$m]) ? $params[$m] : $m;
}, $this->_sql);
}
$sql = '';
foreach (explode('?', $this->_sql) as $i => $part) {
$sql .= (isset($params[$i]) ? $params[$i] : '') . $part;
}
return $sql;
}
Returns the SQL statement for this command.
public string getSql ( ) | ||
return | string |
The SQL statement to be executed |
---|
public function getSql()
{
return $this->_sql;
}
Defined in: yii\base\Component::hasEventHandlers()
Returns a value indicating whether there is any handler attached to the named event.
public boolean hasEventHandlers ( $name ) | ||
$name | string |
The event name |
return | boolean |
Whether there is any handler attached to the event. |
---|
public function hasEventHandlers($name)
{
$this->ensureBehaviors();
if (!empty($this->_events[$name])) {
return true;
}
foreach ($this->_eventWildcards as $wildcard => $handlers) {
if (!empty($handlers) && StringHelper::matchWildcard($wildcard, $name)) {
return true;
}
}
return Event::hasHandlers($this, $name);
}
Defined in: yii\base\Component::hasMethod()
Returns a value indicating whether a method is defined.
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).
public boolean hasMethod ( $name, $checkBehaviors = true ) | ||
$name | string |
The property name |
$checkBehaviors | boolean |
Whether to treat behaviors' methods as methods of this component |
return | boolean |
Whether the method is defined |
---|
public function hasMethod($name, $checkBehaviors = true)
{
if (method_exists($this, $name)) {
return true;
} elseif ($checkBehaviors) {
$this->ensureBehaviors();
foreach ($this->_behaviors as $behavior) {
if ($behavior->hasMethod($name)) {
return true;
}
}
}
return false;
}
Defined in: yii\base\Component::hasProperty()
Returns a value indicating whether a property is defined for this component.
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).
See also:
public boolean hasProperty ( $name, $checkVars = true, $checkBehaviors = true ) | ||
$name | string |
The property name |
$checkVars | boolean |
Whether to treat member variables as properties |
$checkBehaviors | boolean |
Whether to treat behaviors' properties as properties of this component |
return | boolean |
Whether the property is defined |
---|
public function hasProperty($name, $checkVars = true, $checkBehaviors = true)
{
return $this->canGetProperty($name, $checkVars, $checkBehaviors) || $this->canSetProperty($name, false, $checkBehaviors);
}
Defined in: yii\base\BaseObject::init()
Initializes the object.
This method is invoked at the end of the constructor after the object is initialized with the given configuration.
public void init ( ) |
public function init()
{
}
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 Query to perform INSERT INTO ... SELECT SQL statement. Passing of Query is available since version 2.0.11. |
return | $this |
The command object itself |
---|
public function insert($table, $columns)
{
$params = [];
$sql = $this->db->getQueryBuilder()->insert($table, $columns, $params);
return $this->setSql($sql)->bindValues($params);
}
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. |
---|
protected function internalExecute($rawSql)
{
$attempt = 0;
while (true) {
try {
if (
++$attempt === 1
&& $this->_isolationLevel !== false
&& $this->db->getTransaction() === null
) {
$this->db->transaction(function () use ($rawSql) {
$this->internalExecute($rawSql);
}, $this->_isolationLevel);
} else {
$this->pdoStatement->execute();
}
break;
} catch (\Exception $e) {
$rawSql = $rawSql ?: $this->getRawSql();
$e = $this->db->getSchema()->convertException($e, $rawSql);
if ($this->_retryHandler === null || !call_user_func($this->_retryHandler, $e, $attempt)) {
throw $e;
}
}
}
}
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. |
---|
protected function logQuery($category)
{
if ($this->db->enableLogging) {
$rawSql = $this->getRawSql();
Yii::info($rawSql, $category);
}
if (!$this->db->enableProfiling) {
return [false, isset($rawSql) ? $rawSql : null];
}
return [true, isset($rawSql) ? $rawSql : $this->getRawSql()];
}
Disables query cache for this command.
public $this noCache ( ) | ||
return | $this |
The command object itself |
---|
public function noCache()
{
$this->queryCacheDuration = -1;
return $this;
}
Defined in: yii\base\Component::off()
Detaches an existing event handler from this component.
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.
See also on().
public boolean off ( $name, $handler = null ) | ||
$name | string |
Event name |
$handler | callable|null |
The event handler to be removed. If it is null, all handlers attached to the named event will be removed. |
return | boolean |
If a handler is found and detached |
---|
public function off($name, $handler = null)
{
$this->ensureBehaviors();
if (empty($this->_events[$name]) && empty($this->_eventWildcards[$name])) {
return false;
}
if ($handler === null) {
unset($this->_events[$name], $this->_eventWildcards[$name]);
return true;
}
$removed = false;
// plain event names
if (isset($this->_events[$name])) {
foreach ($this->_events[$name] as $i => $event) {
if ($event[0] === $handler) {
unset($this->_events[$name][$i]);
$removed = true;
}
}
if ($removed) {
$this->_events[$name] = array_values($this->_events[$name]);
return true;
}
}
// wildcard event names
if (isset($this->_eventWildcards[$name])) {
foreach ($this->_eventWildcards[$name] as $i => $event) {
if ($event[0] === $handler) {
unset($this->_eventWildcards[$name][$i]);
$removed = true;
}
}
if ($removed) {
$this->_eventWildcards[$name] = array_values($this->_eventWildcards[$name]);
// remove empty wildcards to save future redundant regex checks:
if (empty($this->_eventWildcards[$name])) {
unset($this->_eventWildcards[$name]);
}
}
}
return $removed;
}
Defined in: yii\base\Component::on()
Attaches an event handler to an event.
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 yii\base\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.');
});
See also off().
public void on ( $name, $handler, $data = null, $append = true ) | ||
$name | string |
The event name |
$handler | callable |
The event handler |
$data | mixed |
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 yii\base\Event::$data. |
$append | boolean |
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. |
public function on($name, $handler, $data = null, $append = true)
{
$this->ensureBehaviors();
if (strpos($name, '*') !== false) {
if ($append || empty($this->_eventWildcards[$name])) {
$this->_eventWildcards[$name][] = [$handler, $data];
} else {
array_unshift($this->_eventWildcards[$name], [$handler, $data]);
}
return;
}
if ($append || empty($this->_events[$name])) {
$this->_events[$name][] = [$handler, $data];
} else {
array_unshift($this->_events[$name], [$handler, $data]);
}
}
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|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. |
throws | yii\db\Exception |
if there is any DB error |
---|
public function prepare($forRead = null)
{
if ($this->pdoStatement) {
$this->bindPendingParams();
return;
}
$sql = $this->getSql();
if ($sql === '') {
return;
}
if ($this->db->getTransaction()) {
// master is in a transaction. use the same connection.
$forRead = false;
}
if ($forRead || $forRead === null && $this->db->getSchema()->isReadQuery($sql)) {
$pdo = $this->db->getSlavePdo(true);
} else {
$pdo = $this->db->getMasterPdo();
}
try {
$this->pdoStatement = $pdo->prepare($sql);
$this->bindPendingParams();
} catch (\Exception $e) {
$message = $e->getMessage() . "\nFailed to prepare SQL: $sql";
$errorInfo = $e instanceof \PDOException ? $e->errorInfo : null;
throw new Exception($message, $errorInfo, $e->getCode(), $e);
} catch (\Throwable $e) {
$message = $e->getMessage() . "\nFailed to prepare SQL: $sql";
throw new Exception($message, null, $e->getCode(), $e);
}
}
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 |
public function query()
{
return $this->queryInternal('');
}
Executes the SQL statement and returns ALL rows at once.
public array queryAll ( $fetchMode = null ) | ||
$fetchMode | integer|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. |
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 |
public function queryAll($fetchMode = null)
{
return $this->queryInternal('fetchAll', $fetchMode);
}
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 |
public function queryColumn()
{
return $this->queryInternal('fetchAll', \PDO::FETCH_COLUMN);
}
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|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. |
return | mixed |
The method execution result |
---|---|---|
throws | yii\db\Exception |
if the query causes any problem |
Version | Description |
---|---|
2.0.1 | this method is protected (was private before). |
protected function queryInternal($method, $fetchMode = null)
{
list($profile, $rawSql) = $this->logQuery('yii\db\Command::query');
if ($method !== '') {
$info = $this->db->getQueryCacheInfo($this->queryCacheDuration, $this->queryCacheDependency);
if (is_array($info)) {
/* @var $cache \yii\caching\CacheInterface */
$cache = $info[0];
$cacheKey = $this->getCacheKey($method, $fetchMode, '');
$result = $cache->get($cacheKey);
if (is_array($result) && array_key_exists(0, $result)) {
Yii::debug('Query result served from cache', 'yii\db\Command::query');
return $result[0];
}
}
}
$this->prepare(true);
try {
$profile and Yii::beginProfile($rawSql, 'yii\db\Command::query');
$this->internalExecute($rawSql);
if ($method === '') {
$result = new DataReader($this);
} else {
if ($fetchMode === null) {
$fetchMode = $this->fetchMode;
}
$result = call_user_func_array([$this->pdoStatement, $method], (array) $fetchMode);
$this->pdoStatement->closeCursor();
}
$profile and Yii::endProfile($rawSql, 'yii\db\Command::query');
} catch (Exception $e) {
$profile and Yii::endProfile($rawSql, 'yii\db\Command::query');
throw $e;
}
if (isset($cache, $cacheKey, $info)) {
$cache->set($cacheKey, [$result], $info[1], $info[2]);
Yii::debug('Saved query result in cache', 'yii\db\Command::query');
}
return $result;
}
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|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. |
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 |
public function queryOne($fetchMode = null)
{
return $this->queryInternal('fetch', $fetchMode);
}
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|integer|null|false queryScalar ( ) | ||
return | string|integer|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 |
public function queryScalar()
{
$result = $this->queryInternal('fetchColumn', 0);
if (is_resource($result) && get_resource_type($result) === 'stream') {
return stream_get_contents($result);
}
return $result;
}
Refreshes table schema, which was marked by requireTableSchemaRefresh().
protected void refreshTableSchema ( ) |
protected function refreshTableSchema()
{
if ($this->_refreshTableName !== null) {
$this->db->getSchema()->refreshTableSchema($this->_refreshTableName);
}
}
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 |
---|
public function renameColumn($table, $oldName, $newName)
{
$sql = $this->db->getQueryBuilder()->renameColumn($table, $oldName, $newName);
return $this->setSql($sql)->requireTableSchemaRefresh($table);
}
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 |
---|
public function renameTable($table, $newName)
{
$sql = $this->db->getQueryBuilder()->renameTable($table, $newName);
return $this->setSql($sql)->requireTableSchemaRefresh($table);
}
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 |
---|
protected function requireTableSchemaRefresh($name)
{
$this->_refreshTableName = $name;
return $this;
}
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. |
---|
protected function requireTransaction($isolationLevel = null)
{
$this->_isolationLevel = $isolationLevel;
return $this;
}
Resets command properties to their initial state.
protected void reset ( ) |
protected function reset()
{
$this->_sql = null;
$this->pendingParams = [];
$this->params = [];
$this->_refreshTableName = null;
$this->_isolationLevel = false;
}
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 |
public function resetSequence($table, $value = null)
{
$sql = $this->db->getQueryBuilder()->resetSequence($table, $value);
return $this->setSql($sql);
}
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 |
---|
public function setRawSql($sql)
{
if ($sql !== $this->_sql) {
$this->cancel();
$this->reset();
$this->_sql = $sql;
}
return $this;
}
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. |
---|
protected function setRetryHandler(callable $handler)
{
$this->_retryHandler = $handler;
return $this;
}
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 |
---|
public function setSql($sql)
{
if ($sql !== $this->_sql) {
$this->cancel();
$this->reset();
$this->_sql = $this->db->quoteSql($sql);
}
return $this;
}
Defined in: yii\base\Component::trigger()
Triggers an event.
This method represents the happening of an event. It invokes all attached handlers for the event including class-level handlers.
public void trigger ( $name, yii\base\Event $event = null ) | ||
$name | string |
The event name |
$event | yii\base\Event|null |
The event instance. If not set, a default yii\base\Event object will be created. |
public function trigger($name, Event $event = null)
{
$this->ensureBehaviors();
$eventHandlers = [];
foreach ($this->_eventWildcards as $wildcard => $handlers) {
if (StringHelper::matchWildcard($wildcard, $name)) {
$eventHandlers[] = $handlers;
}
}
if (!empty($this->_events[$name])) {
$eventHandlers[] = $this->_events[$name];
}
if (!empty($eventHandlers)) {
$eventHandlers = call_user_func_array('array_merge', $eventHandlers);
if ($event === null) {
$event = new Event();
}
if ($event->sender === null) {
$event->sender = $this;
}
$event->handled = false;
$event->name = $name;
foreach ($eventHandlers as $handler) {
$event->data = $handler[1];
call_user_func($handler[0], $event);
// stop further handling if the event is handled
if ($event->handled) {
return;
}
}
}
// invoke class-level attached handlers
Event::trigger($this, $name, $event);
}
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 |
---|
public function truncateTable($table)
{
$sql = $this->db->getQueryBuilder()->truncateTable($table);
return $this->setSql($sql);
}
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 |
---|
public function update($table, $columns, $condition = '', $params = [])
{
$sql = $this->db->getQueryBuilder()->update($table, $columns, $condition, $params);
return $this->setSql($sql)->bindValues($params);
}
Creates a command to insert rows into a database table if they do not already exist (matching unique constraints), or update them if they do.
For example,
$sql = $queryBuilder->upsert('pages', [
'name' => 'Front page',
'url' => 'https://example.com/', // url is unique
'visits' => 0,
], [
'visits' => new \yii\db\Expression('visits + 1'),
], $params);
The method will properly escape the table and column names.
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. |
---|
public function upsert($table, $insertColumns, $updateColumns = true, $params = [])
{
$sql = $this->db->getQueryBuilder()->upsert($table, $insertColumns, $updateColumns, $params);
return $this->setSql($sql)->bindValues($params);
}
Signup or Login in order to comment.