Class yii\db\Migration

Inheritanceyii\db\Migration » yii\base\Component » yii\base\BaseObject
Implementsyii\base\Configurable, yii\db\MigrationInterface
Uses Traitsyii\db\SchemaBuilderTrait
Available since version2.0
Source Code https://github.com/yiisoft/yii2/blob/master/framework/db/Migration.php

Migration is the base class for representing a database migration.

Migration is designed to be used together with the "yii migrate" command.

Each child class of Migration represents an individual database migration which is identified by the child class name.

Within each migration, the up() method should be overridden to contain the logic for "upgrading" the database; while the down() method for the "downgrading" logic. The "yii migrate" command manages all available migrations in an application.

If the database supports transactions, you may also override safeUp() and safeDown() so that if anything wrong happens during the upgrading or downgrading, the whole migration can be reverted in a whole.

Note that some DB queries in some DBMS cannot be put into a transaction. For some examples, please refer to implicit commit. If this is the case, you should still implement up() and down(), instead.

Migration provides a set of convenient methods for manipulating database data and schema. For example, the insert() method can be used to easily insert a row of data into a database table; the createTable() method can be used to create a database table. Compared with the same methods in yii\db\Command, these methods will display extra information showing the method parameters and execution time, which may be useful when applying migrations.

For more details and usage information on Migration, see the guide article on Migration.

Public Properties

Hide inherited properties

Property Type Description Defined By
$behaviors yii\base\Behavior[] List of behaviors attached to this component. yii\base\Component
$compact boolean Indicates whether the console output should be compacted. yii\db\Migration
$db yii\db\Connection|array|string The DB connection object or the application component ID of the DB connection that this migration should work with. yii\db\Migration
$maxSqlOutputLength integer Max number of characters of the SQL outputted. yii\db\Migration

Public Methods

Hide inherited 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
addColumn() Builds and executes a SQL statement for adding a new DB column. yii\db\Migration
addCommentOnColumn() Builds and execute a SQL statement for adding comment to column. yii\db\Migration
addCommentOnTable() Builds a SQL statement for adding comment to table. yii\db\Migration
addForeignKey() Builds a SQL statement for adding a foreign key constraint to an existing table. yii\db\Migration
addPrimaryKey() Builds and executes a SQL statement for creating a primary key. yii\db\Migration
alterColumn() Builds and executes a SQL statement for changing the definition of a column. yii\db\Migration
attachBehavior() Attaches a behavior to this component. yii\base\Component
attachBehaviors() Attaches a list of behaviors to the component. yii\base\Component
batchInsert() Creates and executes a batch INSERT SQL statement. yii\db\Migration
behaviors() Returns a list of behaviors that this component should behave as. yii\base\Component
bigInteger() Creates a bigint column. yii\db\SchemaBuilderTrait
bigPrimaryKey() Creates a big primary key column. yii\db\SchemaBuilderTrait
binary() Creates a binary column. yii\db\SchemaBuilderTrait
boolean() Creates a boolean column. yii\db\SchemaBuilderTrait
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
char() Creates a char column. yii\db\SchemaBuilderTrait
className() Returns the fully qualified name of this class. yii\base\BaseObject
createIndex() Builds and executes a SQL statement for creating a new index. yii\db\Migration
createTable() Builds and executes a SQL statement for creating a new DB table. yii\db\Migration
date() Creates a date column. yii\db\SchemaBuilderTrait
dateTime() Creates a datetime column. yii\db\SchemaBuilderTrait
decimal() Creates a decimal column. yii\db\SchemaBuilderTrait
delete() Creates and executes a DELETE SQL statement. yii\db\Migration
detachBehavior() Detaches a behavior from the component. yii\base\Component
detachBehaviors() Detaches all behaviors from the component. yii\base\Component
double() Creates a double column. yii\db\SchemaBuilderTrait
down() This method contains the logic to be executed when removing this migration. yii\db\Migration
dropColumn() Builds and executes a SQL statement for dropping a DB column. yii\db\Migration
dropCommentFromColumn() Builds and execute a SQL statement for dropping comment from column. yii\db\Migration
dropCommentFromTable() Builds a SQL statement for dropping comment from table. yii\db\Migration
dropForeignKey() Builds a SQL statement for dropping a foreign key constraint. yii\db\Migration
dropIndex() Builds and executes a SQL statement for dropping an index. yii\db\Migration
dropPrimaryKey() Builds and executes a SQL statement for dropping a primary key. yii\db\Migration
dropTable() Builds and executes a SQL statement for dropping a DB table. yii\db\Migration
ensureBehaviors() Makes sure that the behaviors declared in behaviors() are attached to this component. yii\base\Component
execute() Executes a SQL statement. yii\db\Migration
float() Creates a float column. yii\db\SchemaBuilderTrait
getBehavior() Returns the named behavior object. yii\base\Component
getBehaviors() Returns all behaviors attached to this component. yii\base\Component
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 migration. yii\db\Migration
insert() Creates and executes an INSERT SQL statement. yii\db\Migration
integer() Creates an integer column. yii\db\SchemaBuilderTrait
json() Creates a JSON column. yii\db\SchemaBuilderTrait
money() Creates a money column. yii\db\SchemaBuilderTrait
off() Detaches an existing event handler from this component. yii\base\Component
on() Attaches an event handler to an event. yii\base\Component
primaryKey() Creates a primary key column. yii\db\SchemaBuilderTrait
renameColumn() Builds and executes a SQL statement for renaming a column. yii\db\Migration
renameTable() Builds and executes a SQL statement for renaming a DB table. yii\db\Migration
safeDown() This method contains the logic to be executed when removing this migration. yii\db\Migration
safeUp() This method contains the logic to be executed when applying this migration. yii\db\Migration
smallInteger() Creates a smallint column. yii\db\SchemaBuilderTrait
string() Creates a string column. yii\db\SchemaBuilderTrait
text() Creates a text column. yii\db\SchemaBuilderTrait
time() Creates a time column. yii\db\SchemaBuilderTrait
timestamp() Creates a timestamp column. yii\db\SchemaBuilderTrait
tinyInteger() Creates a tinyint column. If tinyint is not supported by the DBMS, smallint will be used. yii\db\SchemaBuilderTrait
trigger() Triggers an event. yii\base\Component
truncateTable() Builds and executes a SQL statement for truncating a DB table. yii\db\Migration
up() This method contains the logic to be executed when applying this migration. yii\db\Migration
update() Creates and executes an UPDATE SQL statement. yii\db\Migration
upsert() Creates and executes 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\Migration

Protected Methods

Hide inherited methods

Method Description Defined By
beginCommand() Prepares for a command to be executed, and outputs to the console. yii\db\Migration
endCommand() Finalizes after the command has been executed, and outputs to the console the time elapsed. yii\db\Migration
getDb() yii\db\Migration

Property Details

Hide inherited properties

$compact public property (available since version 2.0.13)

Indicates whether the console output should be compacted. If this is set to true, the individual commands ran within the migration will not be output to the console. Default is false, in other words the output is fully verbose by default.

public boolean $compact false
$db public property

The DB connection object or the application component ID of the DB connection that this migration should work with. Starting from version 2.0.2, this can also be a configuration array for creating the object.

Note that when a Migration object is created by the migrate command, this property will be overwritten by the command. If you do not want to use the DB connection provided by the command, you may override the init() method like the following:

public function init()
{
    $this->db = 'db2';
    parent::init();
}
$maxSqlOutputLength public property (available since version 2.0.13)

Max number of characters of the SQL outputted. Useful for reduction of long statements and making console output more compact.

Method Details

Hide inherited methods

__call() public method

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()");
}

            
__clone() public method

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;
}

            
__construct() public method

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();
}

            
__get() public method

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);
}

            
__isset() public method

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).

See also https://www.php.net/manual/en/function.isset.php.

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;
}

            
__set() public method

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);
}

            
__unset() public method

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).

See also https://www.php.net/manual/en/function.unset.php.

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);
}

            
addColumn() public method

Builds and executes a SQL statement for adding a new DB column.

public void 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. The yii\db\QueryBuilder::getColumnType() method will be invoked to convert abstract column type (if any) into the physical one. Anything that is not recognized as abstract type will be kept in the generated SQL. For example, 'string' will be turned into 'varchar(255)', while 'string not null' will become 'varchar(255) not null'.

                public function addColumn($table, $column, $type)
{
    $time = $this->beginCommand("add column $column $type to table $table");
    $this->db->createCommand()->addColumn($table, $column, $type)->execute();
    if ($type instanceof ColumnSchemaBuilder && $type->comment !== null) {
        $this->db->createCommand()->addCommentOnColumn($table, $column, $type->comment)->execute();
    }
    $this->endCommand($time);
}

            
addCommentOnColumn() public method (available since version 2.0.8)

Builds and execute a SQL statement for adding comment to column.

public void 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.

                public function addCommentOnColumn($table, $column, $comment)
{
    $time = $this->beginCommand("add comment on column $column");
    $this->db->createCommand()->addCommentOnColumn($table, $column, $comment)->execute();
    $this->endCommand($time);
}

            
addCommentOnTable() public method (available since version 2.0.8)

Builds a SQL statement for adding comment to table.

public void addCommentOnTable ( $table, $comment )
$table string

The table 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.

                public function addCommentOnTable($table, $comment)
{
    $time = $this->beginCommand("add comment on table $table");
    $this->db->createCommand()->addCommentOnTable($table, $comment)->execute();
    $this->endCommand($time);
}

            
addForeignKey() public method

Builds a SQL statement for adding a foreign key constraint to an existing table.

The method will properly quote the table and column names.

public void 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 or use an array.

$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 or use an array.

$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

                public function addForeignKey($name, $table, $columns, $refTable, $refColumns, $delete = null, $update = null)
{
    $time = $this->beginCommand("add foreign key $name: $table (" . implode(',', (array) $columns) . ") references $refTable (" . implode(',', (array) $refColumns) . ')');
    $this->db->createCommand()->addForeignKey($name, $table, $columns, $refTable, $refColumns, $delete, $update)->execute();
    $this->endCommand($time);
}

            
addPrimaryKey() public method

Builds and executes a SQL statement for creating a primary key.

The method will properly quote the table and column names.

public void 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.

                public function addPrimaryKey($name, $table, $columns)
{
    $time = $this->beginCommand("add primary key $name on $table (" . (is_array($columns) ? implode(',', $columns) : $columns) . ')');
    $this->db->createCommand()->addPrimaryKey($name, $table, $columns)->execute();
    $this->endCommand($time);
}

            
alterColumn() public method

Builds and executes a SQL statement for changing the definition of a column.

public void 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 new column type. The yii\db\QueryBuilder::getColumnType() method will be invoked to convert abstract column type (if any) into the physical one. Anything that is not recognized as abstract type will be kept in the generated SQL. For example, 'string' will be turned into 'varchar(255)', while 'string not null' will become 'varchar(255) not null'.

                public function alterColumn($table, $column, $type)
{
    $time = $this->beginCommand("alter column $column in table $table to $type");
    $this->db->createCommand()->alterColumn($table, $column, $type)->execute();
    if ($type instanceof ColumnSchemaBuilder && $type->comment !== null) {
        $this->db->createCommand()->addCommentOnColumn($table, $column, $type->comment)->execute();
    }
    $this->endCommand($time);
}

            
attachBehavior() public method

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);
}

            
attachBehaviors() public method

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);
    }
}

            
batchInsert() public method

Creates and executes a batch INSERT SQL statement.

The method will properly escape the column names, and bind the values to be inserted.

public void batchInsert ( $table, $columns, $rows )
$table string

The table that new rows will be inserted into.

$columns array

The column names.

$rows array

The rows to be batch inserted into the table

                public function batchInsert($table, $columns, $rows)
{
    $time = $this->beginCommand("insert into $table");
    $this->db->createCommand()->batchInsert($table, $columns, $rows)->execute();
    $this->endCommand($time);
}

            
beginCommand() protected method (available since version 2.0.13)

Prepares for a command to be executed, and outputs to the console.

protected float beginCommand ( $description )
$description string

The description for the command, to be output to the console.

return float

The time before the command is executed, for the time elapsed to be calculated.

                protected function beginCommand($description)
{
    if (!$this->compact) {
        echo "    > $description ...";
    }
    return microtime(true);
}

            
behaviors() public method

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 [];
}

            
bigInteger() public method (available since version 2.0.6)

Defined in: yii\db\SchemaBuilderTrait::bigInteger()

Creates a bigint column.

public yii\db\ColumnSchemaBuilder bigInteger ( $length null )
$length integer|null

Column size or precision definition. This parameter will be ignored if not supported by the DBMS.

return yii\db\ColumnSchemaBuilder

The column instance which can be further customized.

                public function bigInteger($length = null)
{
    return $this->getDb()->getSchema()->createColumnSchemaBuilder(Schema::TYPE_BIGINT, $length);
}

            
bigPrimaryKey() public method (available since version 2.0.6)

Defined in: yii\db\SchemaBuilderTrait::bigPrimaryKey()

Creates a big primary key column.

public yii\db\ColumnSchemaBuilder bigPrimaryKey ( $length null )
$length integer|null

Column size or precision definition. This parameter will be ignored if not supported by the DBMS.

return yii\db\ColumnSchemaBuilder

The column instance which can be further customized.

                public function bigPrimaryKey($length = null)
{
    return $this->getDb()->getSchema()->createColumnSchemaBuilder(Schema::TYPE_BIGPK, $length);
}

            
binary() public method (available since version 2.0.6)

Defined in: yii\db\SchemaBuilderTrait::binary()

Creates a binary column.

public yii\db\ColumnSchemaBuilder binary ( $length null )
$length integer|null

Column size or precision definition. This parameter will be ignored if not supported by the DBMS.

return yii\db\ColumnSchemaBuilder

The column instance which can be further customized.

                public function binary($length = null)
{
    return $this->getDb()->getSchema()->createColumnSchemaBuilder(Schema::TYPE_BINARY, $length);
}

            
boolean() public method (available since version 2.0.6)

Defined in: yii\db\SchemaBuilderTrait::boolean()

Creates a boolean column.

public yii\db\ColumnSchemaBuilder boolean ( )
return yii\db\ColumnSchemaBuilder

The column instance which can be further customized.

                public function boolean()
{
    return $this->getDb()->getSchema()->createColumnSchemaBuilder(Schema::TYPE_BOOLEAN);
}

            
canGetProperty() public method

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;
}

            
canSetProperty() public method

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;
}

            
char() public method (available since version 2.0.8)

Defined in: yii\db\SchemaBuilderTrait::char()

Creates a char column.

public yii\db\ColumnSchemaBuilder char ( $length null )
$length integer|null

Column size definition i.e. the maximum string length. This parameter will be ignored if not supported by the DBMS.

return yii\db\ColumnSchemaBuilder

The column instance which can be further customized.

                public function char($length = null)
{
    return $this->getDb()->getSchema()->createColumnSchemaBuilder(Schema::TYPE_CHAR, $length);
}

            
className() public static method
Deprecated since 2.0.14. On PHP >=5.5, use ::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();
}

            
createIndex() public method

Builds and executes a SQL statement for creating a new index.

public void 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 or use an array. Each column name will be properly quoted by the method. Quoting will be skipped for column names that include a left parenthesis "(".

$unique boolean

Whether to add UNIQUE constraint on the created index.

                public function createIndex($name, $table, $columns, $unique = false)
{
    $time = $this->beginCommand('create' . ($unique ? ' unique' : '') . " index $name on $table (" . implode(',', (array) $columns) . ')');
    $this->db->createCommand()->createIndex($name, $table, $columns, $unique)->execute();
    $this->endCommand($time);
}

            
createTable() public method

Builds and executes a SQL statement for creating a new DB table.

The columns in the new table should be specified as name-definition pairs (e.g. 'name' => 'string'), where name stands for a column name which will be properly quoted by the method, and definition stands for the column type which can contain an abstract DB type.

The yii\db\QueryBuilder::getColumnType() method will be invoked to convert any abstract type into a physical one.

If a column is specified with definition only (e.g. 'PRIMARY KEY (name, type)'), it will be directly put into the generated SQL.

public void 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.

                public function createTable($table, $columns, $options = null)
{
    $time = $this->beginCommand("create table $table");
    $this->db->createCommand()->createTable($table, $columns, $options)->execute();
    foreach ($columns as $column => $type) {
        if ($type instanceof ColumnSchemaBuilder && $type->comment !== null) {
            $this->db->createCommand()->addCommentOnColumn($table, $column, $type->comment)->execute();
        }
    }
    $this->endCommand($time);
}

            
date() public method (available since version 2.0.6)

Defined in: yii\db\SchemaBuilderTrait::date()

Creates a date column.

public yii\db\ColumnSchemaBuilder date ( )
return yii\db\ColumnSchemaBuilder

The column instance which can be further customized.

                public function date()
{
    return $this->getDb()->getSchema()->createColumnSchemaBuilder(Schema::TYPE_DATE);
}

            
dateTime() public method (available since version 2.0.6)

Defined in: yii\db\SchemaBuilderTrait::dateTime()

Creates a datetime column.

public yii\db\ColumnSchemaBuilder dateTime ( $precision null )
$precision integer|null

Column value precision. First parameter passed to the column type, e.g. DATETIME(precision). This parameter will be ignored if not supported by the DBMS.

return yii\db\ColumnSchemaBuilder

The column instance which can be further customized.

                public function dateTime($precision = null)
{
    return $this->getDb()->getSchema()->createColumnSchemaBuilder(Schema::TYPE_DATETIME, $precision);
}

            
decimal() public method (available since version 2.0.6)

Defined in: yii\db\SchemaBuilderTrait::decimal()

Creates a decimal column.

public yii\db\ColumnSchemaBuilder decimal ( $precision null, $scale null )
$precision integer|null

Column value precision, which is usually the total number of digits. First parameter passed to the column type, e.g. DECIMAL(precision, scale). This parameter will be ignored if not supported by the DBMS.

$scale integer|null

Column value scale, which is usually the number of digits after the decimal point. Second parameter passed to the column type, e.g. DECIMAL(precision, scale). This parameter will be ignored if not supported by the DBMS.

return yii\db\ColumnSchemaBuilder

The column instance which can be further customized.

                public function decimal($precision = null, $scale = null)
{
    $length = [];
    if ($precision !== null) {
        $length[] = $precision;
    }
    if ($scale !== null) {
        $length[] = $scale;
    }
    return $this->getDb()->getSchema()->createColumnSchemaBuilder(Schema::TYPE_DECIMAL, $length);
}

            
delete() public method

Creates and executes a DELETE SQL statement.

public void delete ( $table, $condition '', $params = [] )
$table string

The table where the data will be deleted from.

$condition array|string

The conditions that will be put in the WHERE part. Please refer to yii\db\Query::where() on how to specify conditions.

$params array

The parameters to be bound to the query.

                public function delete($table, $condition = '', $params = [])
{
    $time = $this->beginCommand("delete from $table");
    $this->db->createCommand()->delete($table, $condition, $params)->execute();
    $this->endCommand($time);
}

            
detachBehavior() public method

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;
}

            
detachBehaviors() public method

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);
    }
}

            
double() public method (available since version 2.0.6)

Defined in: yii\db\SchemaBuilderTrait::double()

Creates a double column.

public yii\db\ColumnSchemaBuilder double ( $precision null )
$precision integer|null

Column value precision. First parameter passed to the column type, e.g. DOUBLE(precision). This parameter will be ignored if not supported by the DBMS.

return yii\db\ColumnSchemaBuilder

The column instance which can be further customized.

                public function double($precision = null)
{
    return $this->getDb()->getSchema()->createColumnSchemaBuilder(Schema::TYPE_DOUBLE, $precision);
}

            
down() public method

This method contains the logic to be executed when removing this migration.

The default implementation throws an exception indicating the migration cannot be removed. Child classes may override this method if the corresponding migrations can be removed.

public false|void|mixed down ( )
return false|void|mixed

Return a false value to indicate the migration fails and should not proceed further. All other return values mean the migration succeeds.

                public function down()
{
    $transaction = $this->db->beginTransaction();
    try {
        if ($this->safeDown() === false) {
            $transaction->rollBack();
            return false;
        }
        $transaction->commit();
    } catch (\Exception $e) {
        $this->printException($e);
        $transaction->rollBack();
        return false;
    } catch (\Throwable $e) {
        $this->printException($e);
        $transaction->rollBack();
        return false;
    }
    return null;
}

            
dropColumn() public method

Builds and executes a SQL statement for dropping a DB column.

public void 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.

                public function dropColumn($table, $column)
{
    $time = $this->beginCommand("drop column $column from table $table");
    $this->db->createCommand()->dropColumn($table, $column)->execute();
    $this->endCommand($time);
}

            
dropCommentFromColumn() public method (available since version 2.0.8)

Builds and execute a SQL statement for dropping comment from column.

public void 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.

                public function dropCommentFromColumn($table, $column)
{
    $time = $this->beginCommand("drop comment from column $column");
    $this->db->createCommand()->dropCommentFromColumn($table, $column)->execute();
    $this->endCommand($time);
}

            
dropCommentFromTable() public method (available since version 2.0.8)

Builds a SQL statement for dropping comment from table.

public void dropCommentFromTable ( $table )
$table string

The table whose column is to be commented. The table name will be properly quoted by the method.

                public function dropCommentFromTable($table)
{
    $time = $this->beginCommand("drop comment from table $table");
    $this->db->createCommand()->dropCommentFromTable($table)->execute();
    $this->endCommand($time);
}

            
dropForeignKey() public method

Builds a SQL statement for dropping a foreign key constraint.

public void 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.

                public function dropForeignKey($name, $table)
{
    $time = $this->beginCommand("drop foreign key $name from table $table");
    $this->db->createCommand()->dropForeignKey($name, $table)->execute();
    $this->endCommand($time);
}

            
dropIndex() public method

Builds and executes a SQL statement for dropping an index.

public void 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.

                public function dropIndex($name, $table)
{
    $time = $this->beginCommand("drop index $name on $table");
    $this->db->createCommand()->dropIndex($name, $table)->execute();
    $this->endCommand($time);
}

            
dropPrimaryKey() public method

Builds and executes a SQL statement for dropping a primary key.

public void 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.

                public function dropPrimaryKey($name, $table)
{
    $time = $this->beginCommand("drop primary key $name");
    $this->db->createCommand()->dropPrimaryKey($name, $table)->execute();
    $this->endCommand($time);
}

            
dropTable() public method

Builds and executes a SQL statement for dropping a DB table.

public void dropTable ( $table )
$table string

The table to be dropped. The name will be properly quoted by the method.

                public function dropTable($table)
{
    $time = $this->beginCommand("drop table $table");
    $this->db->createCommand()->dropTable($table)->execute();
    $this->endCommand($time);
}

            
endCommand() protected method (available since version 2.0.13)

Finalizes after the command has been executed, and outputs to the console the time elapsed.

protected void endCommand ( $time )
$time float

The time before the command was executed.

                protected function endCommand($time)
{
    if (!$this->compact) {
        echo ' done (time: ' . sprintf('%.3f', microtime(true) - $time) . "s)\n";
    }
}

            
ensureBehaviors() public method

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);
        }
    }
}

            
execute() public method

Executes a SQL statement.

This method executes the specified SQL statement using $db.

public void execute ( $sql, $params = [] )
$sql string

The SQL statement to be executed

$params array

Input parameters (name => value) for the SQL execution. See yii\db\Command::execute() for more details.

                public function execute($sql, $params = [])
{
    $sqlOutput = $sql;
    if ($this->maxSqlOutputLength !== null) {
        $sqlOutput = StringHelper::truncate($sql, $this->maxSqlOutputLength, '[... hidden]');
    }
    $time = $this->beginCommand("execute SQL: $sqlOutput");
    $this->db->createCommand($sql)->bindValues($params)->execute();
    $this->endCommand($time);
}

            
float() public method (available since version 2.0.6)

Defined in: yii\db\SchemaBuilderTrait::float()

Creates a float column.

public yii\db\ColumnSchemaBuilder float ( $precision null )
$precision integer|null

Column value precision. First parameter passed to the column type, e.g. FLOAT(precision). This parameter will be ignored if not supported by the DBMS.

return yii\db\ColumnSchemaBuilder

The column instance which can be further customized.

                public function float($precision = null)
{
    return $this->getDb()->getSchema()->createColumnSchemaBuilder(Schema::TYPE_FLOAT, $precision);
}

            
getBehavior() public method

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;
}

            
getBehaviors() public method

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;
}

            
getDb() protected method (available since version 2.0.6)

protected void getDb ( )

                protected function getDb()
{
    return $this->db;
}

            
hasEventHandlers() public method

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);
}

            
hasMethod() public method

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;
}

            
hasProperty() public method

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);
}

            
init() public method

Initializes the migration.

This method will set $db to be the 'db' application component, if it is null.

public void init ( )

                public function init()
{
    parent::init();
    $this->db = Instance::ensure($this->db, Connection::className());
    $this->db->getSchema()->refresh();
    $this->db->enableSlaves = false;
}

            
insert() public method

Creates and executes an INSERT SQL statement.

The method will properly escape the column names, and bind the values to be inserted.

public void insert ( $table, $columns )
$table string

The table that new rows will be inserted into.

$columns array

The column data (name => value) to be inserted into the table.

                public function insert($table, $columns)
{
    $time = $this->beginCommand("insert into $table");
    $this->db->createCommand()->insert($table, $columns)->execute();
    $this->endCommand($time);
}

            
integer() public method (available since version 2.0.6)

Defined in: yii\db\SchemaBuilderTrait::integer()

Creates an integer column.

public yii\db\ColumnSchemaBuilder integer ( $length null )
$length integer|null

Column size or precision definition. This parameter will be ignored if not supported by the DBMS.

return yii\db\ColumnSchemaBuilder

The column instance which can be further customized.

                public function integer($length = null)
{
    return $this->getDb()->getSchema()->createColumnSchemaBuilder(Schema::TYPE_INTEGER, $length);
}

            
json() public method (available since version 2.0.14)

Defined in: yii\db\SchemaBuilderTrait::json()

Creates a JSON column.

public yii\db\ColumnSchemaBuilder json ( )
return yii\db\ColumnSchemaBuilder

The column instance which can be further customized.

throws yii\base\Exception

                public function json()
{
    /*
     * TODO Remove in Yii 2.1
     *
     * Disabled due to bug in MySQL extension
     * @link https://bugs.php.net/bug.php?id=70384
     */
    if (version_compare(PHP_VERSION, '5.6', '<') && $this->getDb()->getDriverName() === 'mysql') {
        throw new \yii\base\Exception('JSON column type is not supported in PHP < 5.6');
    }
    return $this->getDb()->getSchema()->createColumnSchemaBuilder(Schema::TYPE_JSON);
}

            
money() public method (available since version 2.0.6)

Defined in: yii\db\SchemaBuilderTrait::money()

Creates a money column.

public yii\db\ColumnSchemaBuilder money ( $precision null, $scale null )
$precision integer|null

Column value precision, which is usually the total number of digits. First parameter passed to the column type, e.g. DECIMAL(precision, scale). This parameter will be ignored if not supported by the DBMS.

$scale integer|null

Column value scale, which is usually the number of digits after the decimal point. Second parameter passed to the column type, e.g. DECIMAL(precision, scale). This parameter will be ignored if not supported by the DBMS.

return yii\db\ColumnSchemaBuilder

The column instance which can be further customized.

                public function money($precision = null, $scale = null)
{
    $length = [];
    if ($precision !== null) {
        $length[] = $precision;
    }
    if ($scale !== null) {
        $length[] = $scale;
    }
    return $this->getDb()->getSchema()->createColumnSchemaBuilder(Schema::TYPE_MONEY, $length);
}

            
off() public method

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;
}

            
on() public method

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]);
    }
}

            
primaryKey() public method (available since version 2.0.6)

Defined in: yii\db\SchemaBuilderTrait::primaryKey()

Creates a primary key column.

public yii\db\ColumnSchemaBuilder primaryKey ( $length null )
$length integer|null

Column size or precision definition. This parameter will be ignored if not supported by the DBMS.

return yii\db\ColumnSchemaBuilder

The column instance which can be further customized.

                public function primaryKey($length = null)
{
    return $this->getDb()->getSchema()->createColumnSchemaBuilder(Schema::TYPE_PK, $length);
}

            
renameColumn() public method

Builds and executes a SQL statement for renaming a column.

public void renameColumn ( $table, $name, $newName )
$table string

The table whose column is to be renamed. The name will be properly quoted by the method.

$name 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.

                public function renameColumn($table, $name, $newName)
{
    $time = $this->beginCommand("rename column $name in table $table to $newName");
    $this->db->createCommand()->renameColumn($table, $name, $newName)->execute();
    $this->endCommand($time);
}

            
renameTable() public method

Builds and executes a SQL statement for renaming a DB table.

public void 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.

                public function renameTable($table, $newName)
{
    $time = $this->beginCommand("rename table $table to $newName");
    $this->db->createCommand()->renameTable($table, $newName)->execute();
    $this->endCommand($time);
}

            
safeDown() public method

This method contains the logic to be executed when removing this migration.

This method differs from down() in that the DB logic implemented here will be enclosed within a DB transaction. Child classes may implement this method instead of down() if the DB logic needs to be within a transaction.

Note: Not all DBMS support transactions. And some DB queries cannot be put into a transaction. For some examples, please refer to implicit commit.

public false|void|mixed safeDown ( )
return false|void|mixed

Return a false value to indicate the migration fails and should not proceed further. All other return values mean the migration succeeds.

                public function safeDown()
{
}

            
safeUp() public method

This method contains the logic to be executed when applying this migration.

This method differs from up() in that the DB logic implemented here will be enclosed within a DB transaction. Child classes may implement this method instead of up() if the DB logic needs to be within a transaction.

Note: Not all DBMS support transactions. And some DB queries cannot be put into a transaction. For some examples, please refer to implicit commit.

public false|void|mixed safeUp ( )
return false|void|mixed

Return a false value to indicate the migration fails and should not proceed further. All other return values mean the migration succeeds.

                public function safeUp()
{
}

            
smallInteger() public method (available since version 2.0.6)

Defined in: yii\db\SchemaBuilderTrait::smallInteger()

Creates a smallint column.

public yii\db\ColumnSchemaBuilder smallInteger ( $length null )
$length integer|null

Column size or precision definition. This parameter will be ignored if not supported by the DBMS.

return yii\db\ColumnSchemaBuilder

The column instance which can be further customized.

                public function smallInteger($length = null)
{
    return $this->getDb()->getSchema()->createColumnSchemaBuilder(Schema::TYPE_SMALLINT, $length);
}

            
string() public method (available since version 2.0.6)

Defined in: yii\db\SchemaBuilderTrait::string()

Creates a string column.

public yii\db\ColumnSchemaBuilder string ( $length null )
$length integer|null

Column size definition i.e. the maximum string length. This parameter will be ignored if not supported by the DBMS.

return yii\db\ColumnSchemaBuilder

The column instance which can be further customized.

                public function string($length = null)
{
    return $this->getDb()->getSchema()->createColumnSchemaBuilder(Schema::TYPE_STRING, $length);
}

            
text() public method (available since version 2.0.6)

Defined in: yii\db\SchemaBuilderTrait::text()

Creates a text column.

public yii\db\ColumnSchemaBuilder text ( )
return yii\db\ColumnSchemaBuilder

The column instance which can be further customized.

                public function text()
{
    return $this->getDb()->getSchema()->createColumnSchemaBuilder(Schema::TYPE_TEXT);
}

            
time() public method (available since version 2.0.6)

Defined in: yii\db\SchemaBuilderTrait::time()

Creates a time column.

public yii\db\ColumnSchemaBuilder time ( $precision null )
$precision integer|null

Column value precision. First parameter passed to the column type, e.g. TIME(precision). This parameter will be ignored if not supported by the DBMS.

return yii\db\ColumnSchemaBuilder

The column instance which can be further customized.

                public function time($precision = null)
{
    return $this->getDb()->getSchema()->createColumnSchemaBuilder(Schema::TYPE_TIME, $precision);
}

            
timestamp() public method (available since version 2.0.6)

Defined in: yii\db\SchemaBuilderTrait::timestamp()

Creates a timestamp column.

public yii\db\ColumnSchemaBuilder timestamp ( $precision null )
$precision integer|null

Column value precision. First parameter passed to the column type, e.g. TIMESTAMP(precision). This parameter will be ignored if not supported by the DBMS.

return yii\db\ColumnSchemaBuilder

The column instance which can be further customized.

                public function timestamp($precision = null)
{
    return $this->getDb()->getSchema()->createColumnSchemaBuilder(Schema::TYPE_TIMESTAMP, $precision);
}

            
tinyInteger() public method (available since version 2.0.14)

Defined in: yii\db\SchemaBuilderTrait::tinyInteger()

Creates a tinyint column. If tinyint is not supported by the DBMS, smallint will be used.

public yii\db\ColumnSchemaBuilder tinyInteger ( $length null )
$length integer|null

Column size or precision definition. This parameter will be ignored if not supported by the DBMS.

return yii\db\ColumnSchemaBuilder

The column instance which can be further customized.

                public function tinyInteger($length = null)
{
    return $this->getDb()->getSchema()->createColumnSchemaBuilder(Schema::TYPE_TINYINT, $length);
}

            
trigger() public method

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);
}

            
truncateTable() public method

Builds and executes a SQL statement for truncating a DB table.

public void truncateTable ( $table )
$table string

The table to be truncated. The name will be properly quoted by the method.

                public function truncateTable($table)
{
    $time = $this->beginCommand("truncate table $table");
    $this->db->createCommand()->truncateTable($table)->execute();
    $this->endCommand($time);
}

            
up() public method

This method contains the logic to be executed when applying this migration.

Child classes may override this method to provide actual migration logic.

public false|void|mixed up ( )
return false|void|mixed

Return a false value to indicate the migration fails and should not proceed further. All other return values mean the migration succeeds.

                public function up()
{
    $transaction = $this->db->beginTransaction();
    try {
        if ($this->safeUp() === false) {
            $transaction->rollBack();
            return false;
        }
        $transaction->commit();
    } catch (\Exception $e) {
        $this->printException($e);
        $transaction->rollBack();
        return false;
    } catch (\Throwable $e) {
        $this->printException($e);
        $transaction->rollBack();
        return false;
    }
    return null;
}

            
update() public method

Creates and executes an UPDATE SQL statement.

The method will properly escape the column names and bind the values to be updated.

public void update ( $table, $columns, $condition '', $params = [] )
$table string

The table to be updated.

$columns array

The column data (name => value) to be updated.

$condition array|string

The conditions that will be put in the WHERE part. Please refer to yii\db\Query::where() on how to specify conditions.

$params array

The parameters to be bound to the query.

                public function update($table, $columns, $condition = '', $params = [])
{
    $time = $this->beginCommand("update $table");
    $this->db->createCommand()->update($table, $columns, $condition, $params)->execute();
    $this->endCommand($time);
}

            
upsert() public method (available since version 2.0.14)

Creates and executes a command to insert rows into a database table if they do not already exist (matching unique constraints), or update them if they do.

The method will properly escape the column names, and bind the values to be inserted.

public void 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 INSERT INTO ... SELECT SQL statement.

$updateColumns array|boolean

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.

$params array

The parameters to be bound to the command.

                public function upsert($table, $insertColumns, $updateColumns = true, $params = [])
{
    $time = $this->beginCommand("upsert into $table");
    $this->db->createCommand()->upsert($table, $insertColumns, $updateColumns, $params)->execute();
    $this->endCommand($time);
}