PHPackages                             bizley/migration - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Database &amp; ORM](/categories/database)
4. /
5. bizley/migration

ActiveYii2-extension[Database &amp; ORM](/categories/database)

bizley/migration
================

Migration generator for Yii 2.

4.4.3(8mo ago)297374.3k↓20.3%38[1 PRs](https://github.com/bizley/yii2-migration/pulls)11Apache-2.0PHPPHP &gt;=7.3CI passing

Since Jul 11Pushed 5mo ago19 watchersCompare

[ Source](https://github.com/bizley/yii2-migration)[ Packagist](https://packagist.org/packages/bizley/migration)[ GitHub Sponsors](https://github.com/sponsors/bizley)[ RSS](/packages/bizley-migration/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (10)Dependencies (5)Versions (75)Used By (11)

[![Yii 2 Migration](yii2-migration.png)](yii2-migration.png)

Yii 2 Migration
===============

[](#yii-2-migration)

[![Latest Stable Version](https://camo.githubusercontent.com/d185a8dd4389fb7f510c313e4c3be4eab71ebeef2323fff4d9c2ae39f2c263f0/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f62697a6c65792f6d6967726174696f6e2e737667)](https://camo.githubusercontent.com/d185a8dd4389fb7f510c313e4c3be4eab71ebeef2323fff4d9c2ae39f2c263f0/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f62697a6c65792f6d6967726174696f6e2e737667)[![Total Downloads](https://camo.githubusercontent.com/0236266b5a0cca88cc96b10f7b32003408789a8013ec84520faabf0a67f1cf1a/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f62697a6c65792f6d6967726174696f6e2e737667)](https://packagist.org/packages/bizley/migration)[![License](https://camo.githubusercontent.com/8f55cec090d103f0f7f894fec21014846bc40abb90096671b95b36e0738d46a2/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f6c2f62697a6c65792f6d6967726174696f6e2e737667)](https://camo.githubusercontent.com/8f55cec090d103f0f7f894fec21014846bc40abb90096671b95b36e0738d46a2/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f6c2f62697a6c65792f6d6967726174696f6e2e737667)[![Infection MSI](https://camo.githubusercontent.com/dff2d67736e2186a1184b242f0a0ca86375a034346280e4178a29b43eac8b7ad/68747470733a2f2f62616467652e737472796b65722d6d757461746f722e696f2f6769746875622e636f6d2f62697a6c65792f796969322d6d6967726174696f6e2f6d6173746572)](https://infection.github.io)

Migration Creator And Updater
-----------------------------

[](#migration-creator-and-updater)

In a perfect world you prepare migration files for your database first so you can run it when ready. But since this is not a perfect world, sometimes you start with a database already set - with this package you can easily **create a migration file** based on your DB schema with **one console command**.

Furthermore, when your DB is updated later on you can **generate a migration file updating the schema** to the current state. The package is comparing it with the migration history:

1. History of applied migrations is scanned to gather all modifications made to the table.
2. Virtual table schema is prepared and compared with the current table schema.
3. Differences are generated as an update migration.
4. In case of the migration history not keeping information about the table, a creating migration is generated.

Installation
------------

[](#installation)

Run console command

```
composer require --dev bizley/migration

```

Or add the package to your `composer.json` file:

```
{
    "require-dev": {
        "bizley/migration": "^4.0"
    }
}
```

then run `composer update`.

Configuration
-------------

[](#configuration)

Add the following in your configuration file (preferably console configuration file):

```
[
    'controllerMap' => [
        'migration' => [
            'class' => 'bizley\migration\controllers\MigrationController',
        ],
    ],
]
```

Additional options are available as following (with their default values):

```
[
    'controllerMap' => [
        'migration' => [
            'class' => 'bizley\migration\controllers\MigrationController',
            'migrationPath' => '@app/migrations', // Directory storing the migration classes
            'migrationNamespace' => null, // Full migration namespace
            'useTablePrefix' => true, // Whether the table names generated should consider the $tablePrefix setting of the DB connection
            'onlyShow' => false, // Whether to only display changes instead of generating update migration
            'fixHistory' => false, // Whether to add generated migration to migration history
            'skipMigrations' => [], // List of migrations from the history table that should be skipped during the update process
            'excludeTables' => [], // List of database tables that should be skipped for actions with "*"
            'fileMode' => null, // Permission to be set for newly generated migration files
            'fileOwnership' => null, // User and/or group ownership to be set for newly generated migration files
            'leeway' => 0, // Leeway in seconds to apply to a starting timestamp when generating migration
        ],
    ],
]
```

Usage
-----

[](#usage)

The following console command are available (assuming you named the controller `migration` like in the example above):

- List all the tables in the database:

    ```
    php yii migration

    ```

    or

    ```
    php yii migration/list

    ```
- Generate migration to create DB table `table_name`:

    ```
    php yii migration/create "table_name"

    ```
- Generate migration to update DB table `table_name`:

    ```
    php yii migration/update "table_name"

    ```

    To generate migrations for all the tables in the database at once (except the excluded ones) use asterisk (\*):

    ```
    php yii migration/create "*"
    php yii migration/update "*"

    ```

    You can generate multiple migrations for many tables at once by separating the names with comma:

    ```
    php yii migration/create "table_name1,table_name2,table_name3"

    ```

    You can provide an asterisk as a part of table name to use all tables matching the pattern:

    ```
    php yii migration/update "prefix_*"

    ```

    Creating multiple table migrations at once forces the proper migration order based on the presence of the foreign keys. When tables are cross-referenced the additional foreign keys migration is generated at the end of default generation.
- Extract SQL statements of migration `migration_name` (UP) **New in 4.4.0**:

    ```
    php yii migration/sql "migration_name"

    ```
- Extract SQL statements of migration `migration_name` (DOWN) **New in 4.4.0**:

    ```
    php yii migration/sql "migration_name" "down"

    ```

Command line parameters
-----------------------

[](#command-line-parameters)

commandaliasdescription`migrationPath``mp`Directory (one or more) storing the migration classes.`migrationNamespace``mn`Namespace (one or more) in case of generating a namespaced migration.`useTablePrefix``tp`Whether the generated table names should consider the `tablePrefix` setting of the DB connection.`migrationTable``mt`Name of the table for keeping the applied migration information.`onlyShow``os`Whether to only display changes instead of generating an update migration.`generalSchema``gs`Whether to use the general column schema instead of the database specific one (see \[1\] below).`fixHistory``fh`Whether to add a migration history entry when the migration is generated.`skipMigrations`List of migrations from the history table that should be skipped during the update process (see \[2\] below).`excludeTables`List of tables that should be skipped.`experimental``ex`Whether to run in the experimental mode (see \[3\] below).`fileMode``fm`Generated file mode to be changed using `chmod`.`fileOwnership``fo`Generated file ownership to be changed using `chown`/`chgrp`.`leeway``lw`The leeway in seconds to apply to a starting timestamp when generating migration, so it can be saved with a later date\[1\] Remember that with different database types, general column schemas may be generated with different length.

> ### MySQL examples:
>
> [](#mysql-examples)
>
> Column `varchar(255)`
> generalSchema=false: `$this->string(255)`
> generalSchema=true: `$this->string()`

> Column `int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY`
> generalSchema=false: `$this->integer(11)->notNull()->append('AUTO_INCREMENT PRIMARY KEY')`
> generalSchema=true: `$this->primaryKey()`

> When column size is different from DBMS' default, it's kept:
> Column `varchar(45)`
> generalSchema=false: `$this->string(45)`
> generalSchema=true: `$this->string(45)`

\[2\] Here you can place the migrations containing actions that cannot be covered by the extractor, i.e. when there is a migration setting the RBAC hierarchy with the authManager component. Such actions should be kept in a separated migration and placed on this list to prevent them from being run during the extraction process.

\[3\] This mode allows using a raw SQL column definition for the migration updater (i.e. `['column' => 'varchar(255)']` instead of `['column' => $this->string()]`). Since the generating process in this mode depends on the individual DBMS syntax the results might not be correct. All help improving this mode is more than welcome.

Important information about RENAMING tables or columns
------------------------------------------------------

[](#important-information-about-renaming-tables-or-columns)

When you rename a table or a column, remember to generate appropriate migration manually, otherwise this extension will not generate an updating migration (in case of the table) or will generate a migration with the command to drop the original column and add a renamed one (in case of the column). This is happening because yii2-migration can only compare two states of the table without the knowledge of how one state turned into another. While the very result of the migration renaming the column and the one dropping it and adding another is the same in terms of structure, the latter **makes you lose data**.

Once you add a renaming migration to the history, it's being tracked by the extension.

Migrating from v2 or v3 to v4
-----------------------------

[](#migrating-from-v2-or-v3-to-v4)

See [Migrating to version 4.0](migrating_to_v4.md) section.

Notes
-----

[](#notes)

This extension should work with all database types supported in Yii 2 core:

- CUBRID (9.3.x and higher)
- MS SQL Server (2008 and above)
- MySQL (4.1.x, 5.x, 8.x)
- Oracle
- PostgreSQL (9.x and above)
- SQLite (2/3)

Only history of the migrations extending `yii\db\Migration` class can be properly scanned, and only changes applied with default `yii\db\Migration` methods can be recognised (except for `execute()`, `addCommentOnTable()`, and `dropCommentFromTable()` methods). Changes made to the table's data (like `insert()`, `upsert()`, `delete()`, `truncate()`, etc.) are not tracked.

Updating migrations process requires for the methods `createTable()`, `addColumn()`, and `alterColumn()` to provide changes in columns definition in the form of an instance of `yii\db\ColumnSchemaBuilder` (like `$this->string()` instead of `'varchar(255)'`).

The new 4.4.0 feature with extracting SQL statements from the existing migration supports all methods available in `yii\db\Migration`.

Tests
-----

[](#tests)

Tests for MySQL, PostgreSQL, and SQLite are provided. Database configuration is stored in `tests/config.php` (you can override it by creating `config.local.php` file there).
Docker Compose file for setting up the databases is stored in `tests/docker`.

Previous versions
-----------------

[](#previous-versions)

These versions are not developed anymore but still available for all poor souls that are stuck with EOL PHP. Some of the newest features may not be available there.

version constraintPHP requirementsYii requirements^3.6&gt;= 7.1&gt;= 2.0.15.1^2.9&lt; 7.12.0.13 to track non-unique indexes, 2.0.14 to handle `TINYINT` and `JSON` type columns.

###  Health Score

60

—

FairBetter than 99% of packages

Maintenance67

Regular maintenance activity

Popularity54

Moderate usage in the ecosystem

Community33

Small or concentrated contributor base

Maturity73

Established project with proven stability

 Bus Factor1

Top contributor holds 57.7% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~46 days

Recently: every ~325 days

Total

73

Last Release

246d ago

Major Versions

2.9.3 → 3.6.32019-11-01

2.9.4 → 4.0.0-RC12020-04-18

2.9.5 → 4.0.0-RC22020-04-24

2.9.6 → 3.x-dev2020-10-03

3.6.6 → 4.1.22020-10-27

PHP version history (5 changes)3.0.0PHP &gt;=7.1.0

2.3.2PHP &gt;=5.4.0 &lt;7.1.0

4.0.0-RC1PHP ^7.2

4.1.3PHP &gt;=7.2

4.4.2PHP &gt;=7.3

### Community

Maintainers

![](https://www.gravatar.com/avatar/b33b799410f9cb8d69a27bce7ae65d5c0a0aa8e097b2624c2f5315400d653b38?d=identicon)[bizley](/maintainers/bizley)

---

Top Contributors

[![dependabot[bot]](https://avatars.githubusercontent.com/in/29110?v=4)](https://github.com/dependabot[bot] "dependabot[bot] (30 commits)")[![bizley](https://avatars.githubusercontent.com/u/8577314?v=4)](https://github.com/bizley "bizley (10 commits)")[![thyseus](https://avatars.githubusercontent.com/u/654271?v=4)](https://github.com/thyseus "thyseus (6 commits)")[![craiglondon](https://avatars.githubusercontent.com/u/3833140?v=4)](https://github.com/craiglondon "craiglondon (2 commits)")[![ecamachoh](https://avatars.githubusercontent.com/u/24883224?v=4)](https://github.com/ecamachoh "ecamachoh (1 commits)")[![krepver](https://avatars.githubusercontent.com/u/1073706?v=4)](https://github.com/krepver "krepver (1 commits)")[![kubk](https://avatars.githubusercontent.com/u/22447849?v=4)](https://github.com/kubk "kubk (1 commits)")[![MarcoMoreno](https://avatars.githubusercontent.com/u/32285738?v=4)](https://github.com/MarcoMoreno "MarcoMoreno (1 commits)")

---

Tags

databasedatabase-migrationsgeneratorhacktoberfestmigrationphpupdateryii2consolemigrationgeneratoryii2migrateupdater

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Type Coverage Yes

### Embed Badge

![Health badge](/badges/bizley-migration/health.svg)

```
[![Health](https://phpackages.com/badges/bizley-migration/health.svg)](https://phpackages.com/packages/bizley-migration)
```

###  Alternatives

[dmstr/yii2-migrate-command

Console Migration Command with multiple paths/aliases support

31295.5k6](/packages/dmstr-yii2-migrate-command)[yii2tech/illuminate

Yii2 to Laravel Migration Package

11315.1k](/packages/yii2tech-illuminate)[e282486518/yii2-console-migration

yii2命令行中使用migration备份和还原数据库

388.1k4](/packages/e282486518-yii2-console-migration)[hzhihua/yii2-dump

Generate the schema from an existing database

1828.5k1](/packages/hzhihua-yii2-dump)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
