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 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 function __clone()
{
$this->_events = [];
$this->_eventWildcards = [];
$this->_behaviors = null;
}
Defined in: yii\base\BaseObject::__construct()
Constructor.
The default implementation does two things:
$config
.If this method is overridden in a child class, it is recommended that
$config
here.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:
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 function __get($name)
{
$getter = 'get' . $name;
if (method_exists($this, $getter)) {
return $this->$getter();
}
$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:
false
for non existing propertiesDo not call this method directly as it is a PHP magic method that will be implicitly called when executing isset($component->property)
.
See also https://www.php.net/manual/en/function.isset.php.
public function __isset($name)
{
$getter = 'get' . $name;
if (method_exists($this, $getter)) {
return $this->$getter() !== null;
}
$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:
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 function __set($name, $value)
{
$setter = 'set' . $name;
if (method_exists($this, $setter)) {
$this->$setter($value);
return;
} elseif (strncmp($name, 'on ', 3) === 0) {
$this->on(trim(substr($name, 3)), $value);
return;
} elseif (strncmp($name, 'as ', 3) === 0) {
$name = trim(substr($name, 3));
if ($value instanceof Behavior) {
$this->attachBehavior($name, $value);
} elseif ($value instanceof \Closure) {
$this->attachBehavior($name, call_user_func($value));
} elseif (isset($value['__class']) && is_subclass_of($value['__class'], Behavior::class)) {
$this->attachBehavior($name, Yii::createObject($value));
} elseif (!isset($value['__class']) && isset($value['class']) && is_subclass_of($value['class'], Behavior::class)) {
$this->attachBehavior($name, Yii::createObject($value));
} elseif (is_string($value) && is_subclass_of($value, Behavior::class, true)) {
$this->attachBehavior($name, Yii::createObject($value));
} else {
throw new InvalidConfigException('Class is not of type ' . Behavior::class . ' or its subclasses');
}
return;
}
$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:
Do not call this method directly as it is a PHP magic method that will be implicitly called when executing unset($component->property)
.
See also https://www.php.net/manual/en/function.unset.php.
public function __unset($name)
{
$setter = 'set' . $name;
if (method_exists($this, $setter)) {
$this->$setter(null);
return;
}
$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);
}
public $this addCheck ( $name, $table, $expression ) $name string
The name of the check constraint. The name will be properly quoted by the method.
$table stringThe table that the check constraint will be added to. The name will be properly quoted by the method.
$expression stringThe SQL of the CHECK
constraint.
The command object itself.
public function addCheck($name, $table, $expression)
{
$sql = $this->db->getQueryBuilder()->addCheck($name, $table, $expression);
return $this->setSql($sql)->requireTableSchemaRefresh($table);
}
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 stringThe name of the new column. The name will be properly quoted by the method.
$type stringThe 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 as varchar(255)
, and string not null
becomes varchar(255) not null
.
The command object itself
public function addColumn($table, $column, $type)
{
$sql = $this->db->getQueryBuilder()->addColumn($table, $column, $type);
return $this->setSql($sql)->requireTableSchemaRefresh($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 stringThe table that the default value constraint will be added to. The name will be properly quoted by the method.
$column stringThe name of the column to that the constraint will be added on. The name will be properly quoted by the method.
$value mixedDefault value.
return $thisThe 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);
}
Defined in: yii\db\Command::addForeignKey()
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 stringThe name of the foreign key constraint.
$table stringThe table that the foreign key constraint will be added to.
$columns string|arrayThe name of the column to that the constraint will be added on. If there are multiple columns, separate them with commas.
$refTable stringThe table that the foreign key references to.
$refColumns string|arrayThe name of the column that the foreign key references to. If there are multiple columns, separate them with commas.
$delete string|nullThe ON DELETE option. Most DBMS support these options: RESTRICT, CASCADE, NO ACTION, SET DEFAULT, SET NULL
$update string|nullThe ON UPDATE option. Most DBMS support these options: RESTRICT, CASCADE, NO ACTION, SET DEFAULT, SET NULL
return $thisThe 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);
}
Defined in: yii\db\Command::addPrimaryKey()
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 stringThe name of the primary key constraint.
$table stringThe table that the primary key constraint will be added to.
$columns string|arrayComma separated string or array of columns that the primary key will consist of.
return $thisThe command object itself.
public function addPrimaryKey($name, $table, $columns)
{
$sql = $this->db->getQueryBuilder()->addPrimaryKey($name, $table, $columns);
return $this->setSql($sql)->requireTableSchemaRefresh($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 stringThe table that the unique constraint will be added to. The name will be properly quoted by the method.
$columns string|arrayThe name of the column to that the constraint will be added on. If there are multiple columns, separate them with commas. The name will be properly quoted by the method.
return $thisThe command object itself.
public function addUnique($name, $table, $columns)
{
$sql = $this->db->getQueryBuilder()->addUnique($name, $table, $columns);
return $this->setSql($sql)->requireTableSchemaRefresh($table);
}
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 stringThe name of the column to be changed. The name will be properly quoted by the method.
$type stringThe column type. yii\db\QueryBuilder::getColumnType() will be called to convert the give column type to the physical one. For example, string
will be converted as varchar(255)
, and string not null
becomes varchar(255) not null
.
The command object itself
public function alterColumn($table, $column, $type)
{
$sql = $this->db->getQueryBuilder()->alterColumn($table, $column, $type);
return $this->setSql($sql)->requireTableSchemaRefresh($table);
}
public function attachBehavior($name, $behavior)
{
$this->ensureBehaviors();
return $this->attachBehaviorInternal($name, $behavior);
}
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);
}
}
Defined in: yii\db\Command::batchInsert()
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 stringThe table that new rows will be inserted into.
$columns arrayThe column names
$rows array|GeneratorThe rows to be batch inserted into the table
return $thisThe 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 function behaviors()
{
return [];
}
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 :name
. For a prepared statement using question mark placeholders, this will be the 1-indexed position of the parameter.
The PHP variable to bind to the SQL statement parameter (passed by reference)
$dataType integer|nullSQL data type of the parameter. If null, the type is determined by the PHP type of the value.
$length integer|nullLength of the data type
$driverOptions mixedThe driver-specific options
return $thisThe 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;
}
protected function bindPendingParams()
{
foreach ($this->pendingParams as $name => $value) {
$this->pdoStatement->bindValue($name, $value[0], $value[1]);
}
$this->pendingParams = [];
}
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 :name
. For a prepared statement using question mark placeholders, this will be the 1-indexed position of the parameter.
The value to bind to the parameter
$dataType integer|nullSQL data type of the parameter. If null, the type is determined by the PHP type of the value.
return $thisThe 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;
}
Defined in: yii\db\Command::bindValues()
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 arrayThe 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)]
.
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)) {
$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;
}
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|nullThe cache dependency associated with the cached query result.
return $thisThe 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:
$checkVars
is true);$checkBehaviors
is true).See also canSetProperty().
public boolean canGetProperty ( $name, $checkVars = true, $checkBehaviors = true ) $name stringThe property name
$checkVars booleanWhether to treat member variables as properties
$checkBehaviors booleanWhether to treat behaviors' properties as properties of this component
return booleanWhether 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:
$checkVars
is true);$checkBehaviors
is true).See also canGetProperty().
public boolean canSetProperty ( $name, $checkVars = true, $checkBehaviors = true ) $name stringThe property name
$checkVars booleanWhether to treat member variables as properties
$checkBehaviors booleanWhether to treat behaviors' properties as properties of this component
return booleanWhether 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;
}
public function cancel()
{
$this->pdoStatement = null;
}
public $this checkIntegrity ( $check = true, $schema = '', $table = '' ) $check boolean
Whether to turn on or off the integrity check.
$schema stringThe schema name of the tables. Defaults to empty string, meaning the current or default schema.
$table stringThe table name.
return $thisThe command object itself
throws yii\base\NotSupportedExceptionif 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);
}
Deprecated since 2.0.14. On PHP >=5.5, use ::class
instead.
public static function className()
{
return get_called_class();
}
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 stringThe table that the new index will be created for. The table name will be properly quoted by the method.
$columns string|arrayThe column(s) that should be included in the index. If there are multiple columns, please separate them by commas. The column names will be properly quoted by the method.
$unique booleanWhether to add UNIQUE constraint on the created index.
return $thisThe 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);
}
Defined in: yii\db\Command::createTable()
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',
]); `
The name of the table to be created. The name will be properly quoted by the method.
$columns arrayThe columns (name => definition) in the new table.
$options string|nullAdditional SQL fragment that will be appended to the generated SQL.
return $thisThe command object itself
public function createTable($table, $columns, $options = null)
{
$sql = $this->db->getQueryBuilder()->createTable($table, $columns, $options);
return $this->setSql($sql)->requireTableSchemaRefresh($table);
}
public function createView($viewName, $subquery)
{
$sql = $this->db->getQueryBuilder()->createView($viewName, $subquery);
return $this->setSql($sql)->requireTableSchemaRefresh($viewName);
}
Defined in: yii\db\Command::delete()
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 stringThe table where the data will be deleted from.
$condition string|arrayThe condition that will be put in the WHERE part. Please refer to yii\db\Query::where() on how to specify condition.
$params arrayThe parameters to be bound to the command
return $thisThe command object itself
public function delete($table, $condition = '', $params = [])
{
$sql = $this->db->getQueryBuilder()->delete($table, $condition, $params);
return $this->setSql($sql)->bindValues($params);
}
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;
}
public function detachBehaviors()
{
$this->ensureBehaviors();
foreach ($this->_behaviors as $name => $behavior) {
$this->detachBehavior($name);
}
}
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 stringThe table whose check constraint is to be dropped. The name will be properly quoted by the method.
return $thisThe command object itself.
public function dropCheck($name, $table)
{
$sql = $this->db->getQueryBuilder()->dropCheck($name, $table);
return $this->setSql($sql)->requireTableSchemaRefresh($table);
}
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 stringThe name of the column to be dropped. The name will be properly quoted by the method.
return $thisThe command object itself
public function dropColumn($table, $column)
{
$sql = $this->db->getQueryBuilder()->dropColumn($table, $column);
return $this->setSql($sql)->requireTableSchemaRefresh($table);
}
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 stringThe table whose default value constraint is to be dropped. The name will be properly quoted by the method.
return $thisThe command object itself.
public function dropDefaultValue($name, $table)
{
$sql = $this->db->getQueryBuilder()->dropDefaultValue($name, $table);
return $this->setSql($sql)->requireTableSchemaRefresh($table);
}
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 stringThe table whose foreign is to be dropped. The name will be properly quoted by the method.
return $thisThe command object itself
public function dropForeignKey($name, $table)
{
$sql = $this->db->getQueryBuilder()->dropForeignKey($name, $table);
return $this->setSql($sql)->requireTableSchemaRefresh($table);
}
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 stringThe table whose index is to be dropped. The name will be properly quoted by the method.
return $thisThe command object itself
public function dropIndex($name, $table)
{
$sql = $this->db->getQueryBuilder()->dropIndex($name, $table);
return $this->setSql($sql)->requireTableSchemaRefresh($table);
}
public $this dropPrimaryKey ( $name, $table ) $name string
The name of the primary key constraint to be removed.
$table stringThe table that the primary key constraint will be removed from.
return $thisThe command object itself
public function dropPrimaryKey($name, $table)
{
$sql = $this->db->getQueryBuilder()->dropPrimaryKey($name, $table);
return $this->setSql($sql)->requireTableSchemaRefresh($table);
}
public $this dropTable ( $table ) $table string
The table to be dropped. The name will be properly quoted by the method.
return $thisThe command object itself
public function dropTable($table)
{
$sql = $this->db->getQueryBuilder()->dropTable($table);
return $this->setSql($sql)->requireTableSchemaRefresh($table);
}
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 stringThe table whose unique constraint is to be dropped. The name will be properly quoted by the method.
return $thisThe command object itself.
public function dropUnique($name, $table)
{
$sql = $this->db->getQueryBuilder()->dropUnique($name, $table);
return $this->setSql($sql)->requireTableSchemaRefresh($table);
}
public $this dropView ( $viewName ) $viewName string
The name of the view to be dropped.
return $thisThe command object itself.
public function dropView($viewName)
{
$sql = $this->db->getQueryBuilder()->dropView($viewName);
return $this->setSql($sql)->requireTableSchemaRefresh($viewName);
}
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 function execute()
{
$sql = $this->getSql();
$params = $this->params;
$statements = $this->splitStatements($sql, $params);
if ($statements === false) {
return parent::execute();
}
$result = null;
foreach ($statements as $statement) {
list($statementSql, $statementParams) = $statement;
$this->setSql($statementSql)->bindValues($statementParams);
$result = parent::execute();
}
$this->setSql($sql)->bindValues($params);
return $result;
}
Defined in: yii\db\Command::executeResetSequence()
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 stringThe name of the table whose primary key sequence is reset
$value mixedThe 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\NotSupportedExceptionif this is not supported by the underlying DBMS
public function executeResetSequence($table, $value = null)
{
return $this->db->getQueryBuilder()->executeResetSequence($table, $value);
}
public function getBehavior($name)
{
$this->ensureBehaviors();
return isset($this->_behaviors[$name]) ? $this->_behaviors[$name] : null;
}
public function getBehaviors()
{
$this->ensureBehaviors();
return $this->_behaviors;
}
protected array getCacheKey ( $method, $fetchMode, $rawSql ) $method string
Method of PDOStatement to be called
$fetchMode integerThe result fetch mode. Please refer to PHP manual for valid fetch modes.
$rawSql return arrayThe 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),
];
}
Defined in: yii\db\Command::getRawSql()
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 stringThe 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;
}
public function getSql()
{
return $this->_sql;
}
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:
$checkBehaviors
is true).The property name
$checkBehaviors booleanWhether to treat behaviors' methods as methods of this component
return booleanWhether 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:
$checkVars
is true);$checkBehaviors
is true).See also:
public boolean hasProperty ( $name, $checkVars = true, $checkBehaviors = true ) $name stringThe property name
$checkVars booleanWhether to treat member variables as properties
$checkBehaviors booleanWhether to treat behaviors' properties as properties of this component
return booleanWhether 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 function init()
{
}
Defined in: yii\db\Command::insert()
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 stringThe table that new rows will be inserted into.
$columns array|yii\db\QueryThe column data (name => value) to be inserted into the table or instance of Query to perform INSERT INTO ... SELECT SQL statement. Passing of Query is available since version 2.0.11.
return $thisThe command object itself
public function insert($table, $columns)
{
$params = [];
$sql = $this->db->getQueryBuilder()->insert($table, $columns, $params);
return $this->setSql($sql)->bindValues($params);
}
Defined in: yii\db\Command::internalExecute()
Executes a prepared statement.
It's a wrapper around \PDOStatement::execute() to support transactions and retry handlers.
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;
}
}
}
}
Defined in: yii\db\Command::logQuery()
Logs the current database query if query logging is enabled and returns the profiling token if profiling is enabled.
protected array logQuery ( $category ) $category stringThe log category.
return arrayArray 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()];
}
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 stringEvent name
$handler callable|nullThe event handler to be removed. If it is null, all handlers attached to the named event will be removed.
return booleanIf 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;
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;
}
}
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]);
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) { ... }
[$object, 'handleClick']
['Page', 'handleClick']
'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 stringThe event name
$handler callableThe event handler
$data mixedThe 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 booleanWhether 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]);
}
}
Defined in: yii\db\Command::prepare()
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|nullWhether this method is called for a read query. If null, it means the SQL statement should be used to determine whether it is for read or write.
throws yii\db\Exceptionif 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()) {
$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);
}
}
Defined in: yii\db\Command::query()
Executes the SQL statement and returns query result.
This method is for executing a SQL query that returns result set, such as SELECT
.
public function query()
{
return $this->queryInternal('');
}
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 arrayAll 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\Exceptionexecution failed
public function queryAll($fetchMode = null)
{
return $this->queryInternal('fetchAll', $fetchMode);
}
Defined in: yii\db\Command::queryColumn()
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 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 stringMethod of PDOStatement to be called
$fetchMode integer|nullThe result fetch mode. Please refer to PHP manual for valid fetch modes. If this parameter is null, the value set in $fetchMode will be used.
return mixedThe method execution result
throws yii\db\Exceptionif the query causes any problem
protected function queryInternal($method, $fetchMode = null)
{
$sql = $this->getSql();
$params = $this->params;
$statements = $this->splitStatements($sql, $params);
if ($statements === false) {
return parent::queryInternal($method, $fetchMode);
}
list($lastStatementSql, $lastStatementParams) = array_pop($statements);
foreach ($statements as $statement) {
list($statementSql, $statementParams) = $statement;
$this->setSql($statementSql)->bindValues($statementParams);
parent::execute();
}
$this->setSql($lastStatementSql)->bindValues($lastStatementParams);
$result = parent::queryInternal($method, $fetchMode);
$this->setSql($sql)->bindValues($params);
return $result;
}
Defined in: yii\db\Command::queryOne()
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|nullThe result fetch mode. Please refer to PHP manual for valid fetch modes. If this parameter is null, the value set in $fetchMode will be used.
return array|falseThe first row (in terms of an array) of the query result. False is returned if the query results in nothing.
throws yii\db\Exceptionexecution failed
public function queryOne($fetchMode = null)
{
return $this->queryInternal('fetch', $fetchMode);
}
Defined in: yii\db\Command::queryScalar()
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 function queryScalar()
{
$result = $this->queryInternal('fetchColumn', 0);
if (is_resource($result) && get_resource_type($result) === 'stream') {
return stream_get_contents($result);
}
return $result;
}
protected function refreshTableSchema()
{
if ($this->_refreshTableName !== null) {
$this->db->getSchema()->refreshTableSchema($this->_refreshTableName);
}
}
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 stringThe old name of the column. The name will be properly quoted by the method.
$newName stringThe new name of the column. The name will be properly quoted by the method.
return $thisThe command object itself
public function renameColumn($table, $oldName, $newName)
{
$sql = $this->db->getQueryBuilder()->renameColumn($table, $oldName, $newName);
return $this->setSql($sql)->requireTableSchemaRefresh($table);
}
protected function requireTableSchemaRefresh($name)
{
$this->_refreshTableName = $name;
return $this;
}
protected function requireTransaction($isolationLevel = null)
{
$this->_isolationLevel = $isolationLevel;
return $this;
}
protected function reset()
{
$this->_sql = null;
$this->pendingParams = [];
$this->params = [];
$this->_refreshTableName = null;
$this->_isolationLevel = false;
}
Defined in: yii\db\Command::resetSequence()
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 stringThe name of the table whose primary key sequence will be reset
$value mixedThe 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 $thisThe command object itself
throws yii\base\NotSupportedExceptionif 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);
}
public function setRawSql($sql)
{
if ($sql !== $this->_sql) {
$this->cancel();
$this->reset();
$this->_sql = $sql;
}
return $this;
}
Defined in: 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:
function (\yii\db\Exception $e, $attempt)
{
}
The callable will recieve a database exception thrown and a current attempt (to execute the command) number starting from 1.
protected function setRetryHandler(callable $handler)
{
$this->_retryHandler = $handler;
return $this;
}
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 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);
if ($event->handled) {
return;
}
}
}
Event::trigger($this, $name, $event);
}
public $this truncateTable ( $table ) $table string
The table to be truncated. The name will be properly quoted by the method.
return $thisThe command object itself
public function truncateTable($table)
{
$sql = $this->db->getQueryBuilder()->truncateTable($table);
return $this->setSql($sql);
}
Defined in: yii\db\Command::update()
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 stringThe table to be updated.
$columns arrayThe column data (name => value) to be updated.
$condition string|arrayThe condition that will be put in the WHERE part. Please refer to yii\db\Query::where() on how to specify condition.
$params arrayThe parameters to be bound to the command
return $thisThe 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);
}
Defined in: 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.
For example,
$sql = $queryBuilder->upsert('pages', [
'name' => 'Front page',
'url' => 'https://example.com/',
'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 stringThe table that new rows will be inserted into/updated in.
$insertColumns array|yii\db\QueryThe column data (name => value) to be inserted into the table or instance of yii\db\Query to perform INSERT INTO ... SELECT
SQL statement.
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. If false
is passed, no update will be performed if the column data already exists.
The parameters to be bound to the command.
return $thisThe 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);
}
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4