Skip to content
PHP Ecosystem
Explore

Migration

API reference › yii › db › Migration

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

PropertyTypeDescriptionDefined by
$behaviors read-onlyarray<yii\base\Behavior<static>>List of behaviors attached to this component.yii\base\Component
$compactboolIndicates whether the console output should be compacted. Default: false. Available since 2.0.13.Migration
$dbConnection|array|stringThe DB connection object or the application component ID of the DB connection that this migration should work with. Default: 'db'.Migration
$maxSqlOutputLengthintMax number of characters of the SQL outputted. Default: null. Available since 2.0.13.Migration
MethodDescriptionDefined by
__construct()Constructor.yii\base\BaseObject
__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
__get()Returns the value of a component property.yii\base\Component
__isset()Checks if a property is set, i.e. defined and not null.yii\base\Component
__set()Sets the value of a component property.yii\base\Component
__unset()Sets a component property to be null.yii\base\Component
addCheck()Creates a SQL command for adding a check constraint to an existing table.Migration
addColumn()Builds and executes a SQL statement for adding a new DB column.Migration
addCommentOnColumn()Builds and execute a SQL statement for adding comment to column.Migration
addCommentOnTable()Builds a SQL statement for adding comment to table.Migration
addForeignKey()Builds a SQL statement for adding a foreign key constraint to an existing table.Migration
addPrimaryKey()Builds and executes a SQL statement for creating a primary key.Migration
alterColumn()Builds and executes a SQL statement for changing the definition of a column.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.Migration
behaviors()Returns a list of behaviors that this component should behave as.yii\base\Component
bigInteger()Creates a bigint column.SchemaBuilderTrait
bigPrimaryKey()Creates a big primary key column.SchemaBuilderTrait
binary()Creates a binary column.SchemaBuilderTrait
boolean()Creates a boolean column.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.SchemaBuilderTrait
className() staticReturns the fully qualified name of this class.yii\base\BaseObject
createIndex()Builds and executes a SQL statement for creating a new index.Migration
createTable()Builds and executes a SQL statement for creating a new DB table.Migration
date()Creates a date column.SchemaBuilderTrait
dateTime()Creates a datetime column.SchemaBuilderTrait
decimal()Creates a decimal column.SchemaBuilderTrait
delete()Creates and executes a DELETE SQL statement.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.SchemaBuilderTrait
down()This method contains the logic to be executed when removing this migration.Migration
dropCheck()Creates a SQL command for dropping a check constraint.Migration
dropColumn()Builds and executes a SQL statement for dropping a DB column.Migration
dropCommentFromColumn()Builds and execute a SQL statement for dropping comment from column.Migration
dropCommentFromTable()Builds a SQL statement for dropping comment from table.Migration
dropForeignKey()Builds a SQL statement for dropping a foreign key constraint.Migration
dropIndex()Builds and executes a SQL statement for dropping an index.Migration
dropPrimaryKey()Builds and executes a SQL statement for dropping a primary key.Migration
dropTable()Builds and executes a SQL statement for dropping a DB table.Migration
ensureBehaviors()Makes sure that the behaviors declared in behaviors() are attached to this component.yii\base\Component
execute()Executes a SQL statement.Migration
float()Creates a float column.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.Migration
insert()Creates and executes an INSERT SQL statement.Migration
integer()Creates an integer column.SchemaBuilderTrait
json()Creates a JSON column.SchemaBuilderTrait
money()Creates a money column.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.SchemaBuilderTrait
renameColumn()Builds and executes a SQL statement for renaming a column.Migration
renameTable()Builds and executes a SQL statement for renaming a DB table.Migration
safeDown()This method contains the logic to be executed when removing this migration.Migration
safeUp()This method contains the logic to be executed when applying this migration.Migration
smallInteger()Creates a smallint column.SchemaBuilderTrait
string()Creates a string column.SchemaBuilderTrait
text()Creates a text column.SchemaBuilderTrait
time()Creates a time column.SchemaBuilderTrait
timestamp()Creates a timestamp column.SchemaBuilderTrait
tinyInteger()Creates a tinyint column. If tinyint is not supported by the DBMS, smallint will be used.SchemaBuilderTrait
trigger()Triggers an event.yii\base\Component
truncateTable()Builds and executes a SQL statement for truncating a DB table.Migration
up()This method contains the logic to be executed when applying this migration.Migration
update()Creates and executes an UPDATE SQL statement.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.Migration
beginCommand() protectedPrepares for a command to be executed, and outputs to the console.Migration
endCommand() protectedFinalizes after the command has been executed, and outputs to the console the time elapsed.Migration
getDb() protectedMigration
public bool $compact = false

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.

Since

2.0.13

public yii\db\Connection|array|string $db = 'db'

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();
}
public int $maxSqlOutputLength = null

Max number of characters of the SQL outputted.

Useful for reduction of long statements and making console output more compact.

Since

2.0.13

public function addCheck(string $name, string $table, string $expression): mixed

Creates a SQL command for adding a check constraint to an existing table.

Parameters

ParameterTypeDescription
$namestringThe name of the check constraint. The name will be properly quoted by the method.
$tablestringThe table that the check constraint will be added to. The name will be properly quoted by the method.
$expressionstringThe SQL of the CHECK constraint.

Returns

mixed

public function addColumn(string $table, string $column, string $type): mixed

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

Parameters

ParameterTypeDescription
$tablestringThe table that the new column will be added to. The table name will be properly quoted by the method.
$columnstringThe name of the new column. The name will be properly quoted by the method.
$typestringThe column type. The 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’.

Returns

mixed

public function addCommentOnColumn(string $table, string $column, string $comment): mixed

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

Parameters

ParameterTypeDescription
$tablestringThe table whose column is to be commented. The table name will be properly quoted by the method.
$columnstringThe name of the column to be commented. The column name will be properly quoted by the method.
$commentstringThe text of the comment to be added. The comment will be properly quoted by the method.

Returns

mixed

Since

2.0.8

public function addCommentOnTable(string $table, string $comment): mixed

Builds a SQL statement for adding comment to table.

Parameters

ParameterTypeDescription
$tablestringThe table to be commented. The table name will be properly quoted by the method.
$commentstringThe text of the comment to be added. The comment will be properly quoted by the method.

Returns

mixed

Since

2.0.8

public function addForeignKey(string $name, string $table, string|array $columns, string $refTable, string|array $refColumns, string|null $delete = null, string|null $update = null): mixed

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

The method will properly quote the table and column names.

Parameters

ParameterTypeDescription
$namestringThe name of the foreign key constraint.
$tablestringThe table that the foreign key constraint will be added to.
$columnsstring|arrayThe 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.
$refTablestringThe table that the foreign key references to.
$refColumnsstring|arrayThe name of the column that the foreign key references to. If there are multiple columns, separate them with commas or use an array.
$deletestring|nullThe ON DELETE option. Most DBMS support these options: RESTRICT, CASCADE, NO ACTION, SET DEFAULT, SET NULL
$updatestring|nullThe ON UPDATE option. Most DBMS support these options: RESTRICT, CASCADE, NO ACTION, SET DEFAULT, SET NULL

Returns

mixed

public function addPrimaryKey(string $name, string $table, string|array $columns): mixed

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

The method will properly quote the table and column names.

Parameters

ParameterTypeDescription
$namestringThe name of the primary key constraint.
$tablestringThe table that the primary key constraint will be added to.
$columnsstring|arrayComma separated string or array of columns that the primary key will consist of.

Returns

mixed

public function alterColumn(string $table, string $column, string $type): mixed

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

Parameters

ParameterTypeDescription
$tablestringThe table whose column is to be changed. The table name will be properly quoted by the method.
$columnstringThe name of the column to be changed. The name will be properly quoted by the method.
$typestringThe new column type. The 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’.

Returns

mixed

public function batchInsert(string $table, array $columns, array $rows): mixed

Creates and executes a batch INSERT SQL statement.

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

Parameters

ParameterTypeDescription
$tablestringThe table that new rows will be inserted into.
$columnsarrayThe column names.
$rowsarrayThe rows to be batch inserted into the table

Returns

mixed

public function createIndex(string $name, string $table, string|array $columns, bool $unique = false): mixed

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

Parameters

ParameterTypeDescription
$namestringThe name of the index. The name will be properly quoted by the method.
$tablestringThe table that the new index will be created for. The table name will be properly quoted by the method.
$columnsstring|arrayThe 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 ”(”.
$uniqueboolWhether to add UNIQUE constraint on the created index.

Returns

mixed

public function createTable(string $table, array $columns, string|null $options = null): mixed

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 must contain an abstract DB type.

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

Example usage:

class m200000_000000_create_table_fruits extends \yii\db\Migration
{
public function safeUp()
{
$this->createTable('{{%fruits}}', [
// ...
'column_name double precision null default null',

Parameters

ParameterTypeDescription
$tablestringThe name of the table to be created. The name will be properly quoted by the method.
$columnsarrayThe columns (name => definition) in the new table.
$optionsstring|nullAdditional SQL fragment that will be appended to the generated SQL.

Returns

mixed

public function delete(string $table, array|string $condition = '', array $params = []): mixed

Creates and executes a DELETE SQL statement.

Parameters

ParameterTypeDescription
$tablestringThe table where the data will be deleted from.
$conditionarray|stringThe conditions that will be put in the WHERE part. Please refer to Query::where() on how to specify conditions.
$paramsarrayThe parameters to be bound to the query.

Returns

mixed

public function down(): false|void|mixed

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.

Returns

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 dropCheck(string $name, string $table): mixed

Creates a SQL command for dropping a check constraint.

Parameters

ParameterTypeDescription
$namestringThe name of the check constraint to be dropped. The name will be properly quoted by the method.
$tablestringThe table whose check constraint is to be dropped. The name will be properly quoted by the method.

Returns

mixed

public function dropColumn(string $table, string $column): mixed

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

Parameters

ParameterTypeDescription
$tablestringThe table whose column is to be dropped. The name will be properly quoted by the method.
$columnstringThe name of the column to be dropped. The name will be properly quoted by the method.

Returns

mixed

public function dropCommentFromColumn(string $table, string $column): mixed

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

Parameters

ParameterTypeDescription
$tablestringThe table whose column is to be commented. The table name will be properly quoted by the method.
$columnstringThe name of the column to be commented. The column name will be properly quoted by the method.

Returns

mixed

Since

2.0.8

public function dropCommentFromTable(string $table): mixed

Builds a SQL statement for dropping comment from table.

Parameters

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

Returns

mixed

Since

2.0.8

public function dropForeignKey(string $name, string $table): mixed

Builds a SQL statement for dropping a foreign key constraint.

Parameters

ParameterTypeDescription
$namestringThe name of the foreign key constraint to be dropped. The name will be properly quoted by the method.
$tablestringThe table whose foreign is to be dropped. The name will be properly quoted by the method.

Returns

mixed

public function dropIndex(string $name, string $table): mixed

Builds and executes a SQL statement for dropping an index.

Parameters

ParameterTypeDescription
$namestringThe name of the index to be dropped. The name will be properly quoted by the method.
$tablestringThe table whose index is to be dropped. The name will be properly quoted by the method.

Returns

mixed

public function dropPrimaryKey(string $name, string $table): mixed

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

Parameters

ParameterTypeDescription
$namestringThe name of the primary key constraint to be removed.
$tablestringThe table that the primary key constraint will be removed from.

Returns

mixed

public function dropTable(string $table): mixed

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

Parameters

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

Returns

mixed

public function execute(string $sql, array $params = []): mixed

Executes a SQL statement.

This method executes the specified SQL statement using $db.

Parameters

ParameterTypeDescription
$sqlstringThe SQL statement to be executed
$paramsarrayInput parameters (name => value) for the SQL execution. See Command::execute() for more details.

Returns

mixed

public function init(): mixed

Initializes the migration.

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

Returns

mixed

public function insert(string $table, array $columns): mixed

Creates and executes an INSERT SQL statement.

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

Parameters

ParameterTypeDescription
$tablestringThe table that new rows will be inserted into.
$columnsarrayThe column data (name => value) to be inserted into the table.

Returns

mixed

public function renameColumn(string $table, string $name, string $newName): mixed

Builds and executes a SQL statement for renaming a column.

Parameters

ParameterTypeDescription
$tablestringThe table whose column is to be renamed. The name will be properly quoted by the method.
$namestringThe old name of the column. The name will be properly quoted by the method.
$newNamestringThe new name of the column. The name will be properly quoted by the method.

Returns

mixed

public function renameTable(string $table, string $newName): mixed

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

Parameters

ParameterTypeDescription
$tablestringThe table to be renamed. The name will be properly quoted by the method.
$newNamestringThe new table name. The name will be properly quoted by the method.

Returns

mixed

public function safeDown(): false|void|mixed

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.

Returns

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(): false|void|mixed

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.

Returns

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 truncateTable(string $table): mixed

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

Parameters

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

Returns

mixed

public function up(): false|void|mixed

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

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

Returns

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 update(string $table, array $columns, array|string $condition = '', array $params = []): mixed

Creates and executes an UPDATE SQL statement.

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

Parameters

ParameterTypeDescription
$tablestringThe table to be updated.
$columnsarrayThe column data (name => value) to be updated.
$conditionarray|stringThe conditions that will be put in the WHERE part. Please refer to Query::where() on how to specify conditions.
$paramsarrayThe parameters to be bound to the query.

Returns

mixed

public function upsert(string $table, array|yii\db\Query $insertColumns, array|bool $updateColumns = true, array $params = []): mixed

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.

Parameters

ParameterTypeDescription
$tablestringThe table that new rows will be inserted into/updated in.
$insertColumnsarray|QueryThe column data (name => value) to be inserted into the table or instance of Query to perform INSERT INTO ... SELECT SQL statement.
$updateColumnsarray|boolThe 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.
$paramsarrayThe parameters to be bound to the command.

Returns

mixed

Since

2.0.14

protected function beginCommand(string $description): float

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

Parameters

ParameterTypeDescription
$descriptionstringThe description for the command, to be output to the console.

Returns

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

Since

2.0.13

protected function endCommand(float $time): mixed

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

Parameters

ParameterTypeDescription
$timefloatThe time before the command was executed.

Returns

mixed

Since

2.0.13

protected function getDb()

Since

2.0.6