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.
Properties
Section titled “Properties”| Property | Type | Description | Defined by |
|---|---|---|---|
$behaviors read-only | array<yii\<static>> | List of behaviors attached to this component. | yii\ |
$compact | bool | Indicates whether the console output should be compacted. Default: false. Available since 2.0.13. | Migration |
$db | Connection| | The DB connection object or the application component ID of the DB connection that this migration should work with. Default: 'db'. | Migration |
$maxSqlOutputLength | int | Max number of characters of the SQL outputted. Default: null. Available since 2.0.13. | Migration |
Methods
Section titled “Methods”| Method | Description | Defined by |
|---|---|---|
__construct() | Constructor. | yii\ |
__call() | Calls the named method which is not a class method. | yii\ |
__clone() | This method is called after the object is created by cloning an existing one. | yii\ |
__get() | Returns the value of a component property. | yii\ |
__isset() | Checks if a property is set, i.e. defined and not null. | yii\ |
__set() | Sets the value of a component property. | yii\ |
__unset() | Sets a component property to be null. | yii\ |
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\ |
attachBehaviors() | Attaches a list of behaviors to the component. | yii\ |
batchInsert() | Creates and executes a batch INSERT SQL statement. | Migration |
behaviors() | Returns a list of behaviors that this component should behave as. | yii\ |
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\ |
canSetProperty() | Returns a value indicating whether a property can be set. | yii\ |
char() | Creates a char column. | SchemaBuilderTrait |
className() static | Returns the fully qualified name of this class. | yii\ |
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\ |
detachBehaviors() | Detaches all behaviors from the component. | yii\ |
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\ |
execute() | Executes a SQL statement. | Migration |
float() | Creates a float column. | SchemaBuilderTrait |
getBehavior() | Returns the named behavior object. | yii\ |
getBehaviors() | Returns all behaviors attached to this component. | yii\ |
hasEventHandlers() | Returns a value indicating whether there is any handler attached to the named event. | yii\ |
hasMethod() | Returns a value indicating whether a method is defined. | yii\ |
hasProperty() | Returns a value indicating whether a property is defined for this component. | yii\ |
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\ |
on() | Attaches an event handler to an event. | yii\ |
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\ |
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() protected | Prepares for a command to be executed, and outputs to the console. | Migration |
endCommand() protected | Finalizes after the command has been executed, and outputs to the console the time elapsed. | Migration |
getDb() protected | Migration |
Property details
Section titled “Property details”$compact
Section titled “$compact ”public bool $compact = falseIndicates 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();}$maxSqlOutputLength
Section titled “$maxSqlOutputLength ”public int $maxSqlOutputLength = nullMax number of characters of the SQL outputted.
Useful for reduction of long statements and making console output more compact.
Since
2.0.13
Method details
Section titled “Method details”addCheck()
Section titled “addCheck() ”public function addCheck(string $name, string $table, string $expression): mixedCreates a SQL command for adding a check constraint to an existing table.
Parameters
| Parameter | Type | Description |
|---|---|---|
$name | string | The name of the check constraint. The name will be properly quoted by the method. |
$table | string | The table that the check constraint will be added to. The name will be properly quoted by the method. |
$expression | string | The SQL of the CHECK constraint. |
Returns
mixed
addColumn()
Section titled “addColumn() ”public function addColumn(string $table, string $column, string $type): mixedBuilds and executes a SQL statement for adding a new DB column.
Parameters
| Parameter | Type | Description |
|---|---|---|
$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 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
addCommentOnColumn()
Section titled “addCommentOnColumn() ”public function addCommentOnColumn(string $table, string $column, string $comment): mixedBuilds and execute a SQL statement for adding comment to column.
Parameters
| Parameter | Type | Description |
|---|---|---|
$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. |
Returns
mixed
Since
2.0.8
addCommentOnTable()
Section titled “addCommentOnTable() ”public function addCommentOnTable(string $table, string $comment): mixedBuilds a SQL statement for adding comment to table.
Parameters
| Parameter | Type | Description |
|---|---|---|
$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. |
Returns
mixed
Since
2.0.8
addForeignKey()
Section titled “addForeignKey() ”public function addForeignKey(string $name, string $table, string|array $columns, string $refTable, string|array $refColumns, string|null $delete = null, string|null $update = null): mixedBuilds a SQL statement for adding a foreign key constraint to an existing table.
The method will properly quote the table and column names.
Parameters
| Parameter | Type | Description |
|---|---|---|
$name | string | The name of the foreign key constraint. |
$table | string | The table that the foreign key constraint will be added to. |
$columns | string| | 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| | 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| | The ON DELETE option. Most DBMS support these options: RESTRICT, CASCADE, NO ACTION, SET DEFAULT, SET NULL |
$update | string| | The ON UPDATE option. Most DBMS support these options: RESTRICT, CASCADE, NO ACTION, SET DEFAULT, SET NULL |
Returns
mixed
addPrimaryKey()
Section titled “addPrimaryKey() ”public function addPrimaryKey(string $name, string $table, string|array $columns): mixedBuilds and executes a SQL statement for creating a primary key.
The method will properly quote the table and column names.
Parameters
| Parameter | Type | Description |
|---|---|---|
$name | string | The name of the primary key constraint. |
$table | string | The table that the primary key constraint will be added to. |
$columns | string| | Comma separated string or array of columns that the primary key will consist of. |
Returns
mixed
alterColumn()
Section titled “alterColumn() ”public function alterColumn(string $table, string $column, string $type): mixedBuilds and executes a SQL statement for changing the definition of a column.
Parameters
| Parameter | Type | Description |
|---|---|---|
$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 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
batchInsert()
Section titled “batchInsert() ”public function batchInsert(string $table, array $columns, array $rows): mixedCreates and executes a batch INSERT SQL statement.
The method will properly escape the column names, and bind the values to be inserted.
Parameters
| Parameter | Type | Description |
|---|---|---|
$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 |
Returns
mixed
createIndex()
Section titled “createIndex() ”public function createIndex(string $name, string $table, string|array $columns, bool $unique = false): mixedBuilds and executes a SQL statement for creating a new index.
Parameters
| Parameter | Type | Description |
|---|---|---|
$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| | 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 | bool | Whether to add UNIQUE constraint on the created index. |
Returns
mixed
createTable()
Section titled “createTable() ”public function createTable(string $table, array $columns, string|null $options = null): mixedBuilds 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
| Parameter | Type | Description |
|---|---|---|
$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| | Additional SQL fragment that will be appended to the generated SQL. |
Returns
mixed
delete()
Section titled “delete() ”public function delete(string $table, array|string $condition = '', array $params = []): mixedCreates and executes a DELETE SQL statement.
Parameters
| Parameter | Type | Description |
|---|---|---|
$table | string | The table where the data will be deleted from. |
$condition | array| | The conditions that will be put in the WHERE part. Please refer to Query::where() on how to specify conditions. |
$params | array | The parameters to be bound to the query. |
Returns
mixed
down()
Section titled “down() ”public function down(): false|void|mixedThis 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.
dropCheck()
Section titled “dropCheck() ”public function dropCheck(string $name, string $table): mixedCreates a SQL command for dropping a check constraint.
Parameters
| Parameter | Type | Description |
|---|---|---|
$name | string | The name of the check constraint to be dropped. The name will be properly quoted by the method. |
$table | string | The table whose check constraint is to be dropped. The name will be properly quoted by the method. |
Returns
mixed
dropColumn()
Section titled “dropColumn() ”public function dropColumn(string $table, string $column): mixedBuilds and executes a SQL statement for dropping a DB column.
Parameters
| Parameter | Type | Description |
|---|---|---|
$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. |
Returns
mixed
dropCommentFromColumn()
Section titled “dropCommentFromColumn() ”public function dropCommentFromColumn(string $table, string $column): mixedBuilds and execute a SQL statement for dropping comment from column.
Parameters
| Parameter | Type | Description |
|---|---|---|
$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. |
Returns
mixed
Since
2.0.8
dropCommentFromTable()
Section titled “dropCommentFromTable() ”public function dropCommentFromTable(string $table): mixedBuilds a SQL statement for dropping comment from table.
Parameters
| Parameter | Type | Description |
|---|---|---|
$table | string | The table whose column is to be commented. The table name will be properly quoted by the method. |
Returns
mixed
Since
2.0.8
dropForeignKey()
Section titled “dropForeignKey() ”public function dropForeignKey(string $name, string $table): mixedBuilds a SQL statement for dropping a foreign key constraint.
Parameters
| Parameter | Type | Description |
|---|---|---|
$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. |
Returns
mixed
dropIndex()
Section titled “dropIndex() ”public function dropIndex(string $name, string $table): mixedBuilds and executes a SQL statement for dropping an index.
Parameters
| Parameter | Type | Description |
|---|---|---|
$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. |
Returns
mixed
dropPrimaryKey()
Section titled “dropPrimaryKey() ”public function dropPrimaryKey(string $name, string $table): mixedBuilds and executes a SQL statement for dropping a primary key.
Parameters
| Parameter | Type | Description |
|---|---|---|
$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. |
Returns
mixed
dropTable()
Section titled “dropTable() ”public function dropTable(string $table): mixedBuilds and executes a SQL statement for dropping a DB table.
Parameters
| Parameter | Type | Description |
|---|---|---|
$table | string | The table to be dropped. The name will be properly quoted by the method. |
Returns
mixed
execute()
Section titled “execute() ”public function execute(string $sql, array $params = []): mixedExecutes a SQL statement.
This method executes the specified SQL statement using $db.
Parameters
| Parameter | Type | Description |
|---|---|---|
$sql | string | The SQL statement to be executed |
$params | array | Input parameters (name => value) for the SQL execution. See Command::execute() for more details. |
Returns
mixed
init()
Section titled “init() ”public function init(): mixedInitializes the migration.
This method will set $db to be the ‘db’ application component, if it is null.
Returns
mixed
insert()
Section titled “insert() ”public function insert(string $table, array $columns): mixedCreates and executes an INSERT SQL statement.
The method will properly escape the column names, and bind the values to be inserted.
Parameters
| Parameter | Type | Description |
|---|---|---|
$table | string | The table that new rows will be inserted into. |
$columns | array | The column data (name => value) to be inserted into the table. |
Returns
mixed
renameColumn()
Section titled “renameColumn() ”public function renameColumn(string $table, string $name, string $newName): mixedBuilds and executes a SQL statement for renaming a column.
Parameters
| Parameter | Type | Description |
|---|---|---|
$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. |
Returns
mixed
renameTable()
Section titled “renameTable() ”public function renameTable(string $table, string $newName): mixedBuilds and executes a SQL statement for renaming a DB table.
Parameters
| Parameter | Type | Description |
|---|---|---|
$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. |
Returns
mixed
safeDown()
Section titled “safeDown() ”public function safeDown(): false|void|mixedThis 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.
safeUp()
Section titled “safeUp() ”public function safeUp(): false|void|mixedThis 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.
truncateTable()
Section titled “truncateTable() ”public function truncateTable(string $table): mixedBuilds and executes a SQL statement for truncating a DB table.
Parameters
| Parameter | Type | Description |
|---|---|---|
$table | string | The table to be truncated. The name will be properly quoted by the method. |
Returns
mixed
public function up(): false|void|mixedThis 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.
update()
Section titled “update() ”public function update(string $table, array $columns, array|string $condition = '', array $params = []): mixedCreates and executes an UPDATE SQL statement.
The method will properly escape the column names and bind the values to be updated.
Parameters
| Parameter | Type | Description |
|---|---|---|
$table | string | The table to be updated. |
$columns | array | The column data (name => value) to be updated. |
$condition | array| | The conditions that will be put in the WHERE part. Please refer to Query::where() on how to specify conditions. |
$params | array | The parameters to be bound to the query. |
Returns
mixed
upsert()
Section titled “upsert() ”public function upsert(string $table, array|yii\db\Query $insertColumns, array|bool $updateColumns = true, array $params = []): mixedCreates 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
| Parameter | Type | Description |
|---|---|---|
$table | string | The table that new rows will be inserted into/updated in. |
$insertColumns | array|Query | The column data (name => value) to be inserted into the table or instance of Query to perform INSERT INTO ... SELECT SQL statement. |
$updateColumns | array| | 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. |
Returns
mixed
Since
2.0.14
beginCommand()
Section titled “beginCommand() ”protected function beginCommand(string $description): floatPrepares for a command to be executed, and outputs to the console.
Parameters
| Parameter | Type | Description |
|---|---|---|
$description | string | The 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
endCommand()
Section titled “endCommand() ”protected function endCommand(float $time): mixedFinalizes after the command has been executed, and outputs to the console the time elapsed.
Parameters
| Parameter | Type | Description |
|---|---|---|
$time | float | The time before the command was executed. |
Returns
mixed
Since
2.0.13