PHPackages                             carono/yii2-migrate - 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. carono/yii2-migrate

ActiveLibrary[Database &amp; ORM](/categories/database)

carono/yii2-migrate
===================

Trait to help create databases in migrations for Yii2

1.1.6(2y ago)48.4k↓37.3%1MITPHPPHP &gt;=5.6.0

Since Sep 27Pushed 2y ago2 watchersCompare

[ Source](https://github.com/carono/yii2-migrate)[ Packagist](https://packagist.org/packages/carono/yii2-migrate)[ RSS](/packages/carono-yii2-migrate/feed)WikiDiscussions master Synced 3d ago

READMEChangelogDependencies (1)Versions (25)Used By (1)

[![Scrutinizer Code Quality](https://camo.githubusercontent.com/cbaf45ff4cd158ea412139f92d2ecdd330f6618f5442c849b7c7a10c00e44dbe/68747470733a2f2f7363727574696e697a65722d63692e636f6d2f672f6361726f6e6f2f796969322d6d6967726174652f6261646765732f7175616c6974792d73636f72652e706e673f623d6d6173746572)](https://scrutinizer-ci.com/g/carono/yii2-migrate/?branch=master)[![Latest Stable Version](https://camo.githubusercontent.com/96f408dfb1a08a8afc2f51609a893502f8e3f05cc307096246d3a7a5905cf827/68747470733a2f2f706f7365722e707567782e6f72672f6361726f6e6f2f796969322d6d6967726174652f762f737461626c65)](https://packagist.org/packages/carono/yii2-migrate)[![Total Downloads](https://camo.githubusercontent.com/4829151d8f5307e31c0821e7d14faf287ecd8ed67ec6b90b1e0b0a77108e4544/68747470733a2f2f706f7365722e707567782e6f72672f6361726f6e6f2f796969322d6d6967726174652f646f776e6c6f616473)](https://packagist.org/packages/carono/yii2-migrate)[![License](https://camo.githubusercontent.com/a9751cf11a46b29e78a94601987f5fb123a6475556b2c8f5129c92566e0be56b/68747470733a2f2f706f7365722e707567782e6f72672f6361726f6e6f2f796969322d6d6967726174652f6c6963656e7365)](https://packagist.org/packages/carono/yii2-migrate)[![Build Status](https://camo.githubusercontent.com/23b19598bc4d8801dede146b508ce63e3b68f3546bcca99aae91f2c5ea58e84a/68747470733a2f2f7472617669732d63692e6f72672f6361726f6e6f2f796969322d6d6967726174652e7376673f6272616e63683d6d6173746572)](https://travis-ci.org/carono/yii2-migrate)[![Code Coverage](https://camo.githubusercontent.com/3146a4c618a34028978d52f91f9608d850e3df7276c74a2deb5cfe239cc4a36e/68747470733a2f2f7363727574696e697a65722d63692e636f6d2f672f6361726f6e6f2f796969322d6d6967726174652f6261646765732f636f7665726167652e706e673f623d6d6173746572)](https://scrutinizer-ci.com/g/carono/yii2-migrate/?branch=master)

\[[ENG](README.md)\] \[[RUS](README_RUS.md)\]

MigrationTrait
==============

[](#migrationtrait)

To expand the migration capabilities, you must add a trait **\\carono\\yii2migrate\\traits\\MigrationTrait** or extend the migration class from **\\carono\\yii2migrate\\Migration**

public function tableOptions()
------------------------------

[](#public-function-tableoptions)

Return the array with the settings for creating tables, where the key is the name of the db driver.
When creating tables through createTable(), if no properties are specified, they will be picked up from this function

```
    public function tableOptions()
    {
        return [
            'mysql' => 'CHARACTER SET utf8 COLLATE utf8_general_ci ENGINE=InnoDB'
        ];
    }
```

public function newTables()
---------------------------

[](#public-function-newtables)

Return an array where the key is the name of the table, and the values are columns with types.
If you call the **$this-&gt;upNewTables()** function, all specified tables will be created via createTable()
If you call the function **$this-&gt;downNewTables()**, all specified table will be deleted using dropTable()

```
    public function newTables()
    {
        return [
            '{{%logs}}' => [
                'data' => $this->string(),
                '@tableOptions' => [
                    'mysql' => 'CHARACTER SET utf8 COLLATE utf8_general_ci ENGINE=MyISAM'
                ]
            ]
        ];
    }

    public function safeUp()
    {
        $this->upNewTables();
    }

    public function safeUp()
    {
        $this->downNewTables();
    }
```

pubic function newColumns()
---------------------------

[](#pubic-function-newcolumns)

Return an array where the key is the name of an existing table and the values are columns with types.
If you call the function **$this-&gt;upNewColumns()**, all specified columns will be created using addColumn()
If you call the function **$this-&gt;downNewColumns()**, all specified columns will be deleted after dropColumn()

```
    public function newColumns()
    {
        return [
            '{{%company}}' => [
                'address' => $this->string(),
                'is_active' => $this->boolean()
            ]
        ];
    }

    public function safeUp()
    {
        $this->upNewColumns();
    }

    public function safeUp()
    {
        $this->downNewColumns();
    }
```

public function newIndex()
--------------------------

[](#public-function-newindex)

Return an array where the key is the name of an existing table and the values are the index parameters via $this-&gt;index()
If you call the **$this-&gt;upNewIndex()** function, all specified indexes will be created via createIndex()
If you call the function **$this-&gt;downNewIndex()**, all specified columns will be deleted using the dropIndex()

```
    public function newIndex()
    {
        return [
            '{{%company}}' => [
                $this->index()->columns(['name'])->unique(true)
            ],
        ];
    }

    public function safeUp()
    {
        $this->upNewIndex();
    }

    public function safeUp()
    {
        $this->downNewIndex();
    }
```

Working with foreign keys
=========================

[](#working-with-foreign-keys)

Create a table, specifying a foreign key, by table name only

```
$this->createTable('{{%user}}', [
    'id' => $this->primaryKey(),
    'company_id' => $this->foreignKey('{{%company}}')
]);
```

Adding a foreign key column

```
$this->addColumn('{{%user}}', 'company_id', $this->foreignKey('{{%company}}'));
```

Adding a foreign key to an existing column

```
$this->alterColumn('{{%user}}', 'company_id', $this->foreignKey('{{%company}}'));
```

Adding foreign key with auto name

```
$this->addForeignKey(null, '{{%user}}', 'photo_id', '{{%photo}}', 'id');
```

Delete foreign key by column name

```
$this->dropForeignKeyByColumn('{{%user}}', 'company_id');
```

Working with indexes
====================

[](#working-with-indexes)

Create an index with an automatic name

```
$this->createIndex(null, '{{%user}}', 'name');
```

Deleting an index by column name

```
$this->dropIndexByColumn('{{%user}}', 'name');
```

**(!)** It is necessary to pay attention, if there are several columns on the index, then it is necessary to specify them in the necessary sequence. If there are several indexes with such a set and sequence, all of them will be deleted. **(!)** Does not work correctly with postgreSQL ([yiisoft/yii2#16639](https://github.com/yiisoft/yii2/issues/16639))

```
$this->createIndex(null, '{{%user}}', ['name', 'surname']);
$this->dropIndexByColumn('{{%user}}', ['name', 'surname']);
```

Pivot tables
============

[](#pivot-tables)

To implement many-to-many tables, you can use the $this-&gt;pivot() function, a table with 2 keys will be created. The names of the keys in the PivotTable are generated automatically, so they can be set via refColumn() and sourceColumn()

Create a PivotTable by creating a table. The result is the table {{%user}}\[id\] {{%pv\_user\_photos}}\[user\_id, photo\_id\]

```
$this->createTable('{{%user}}', ['id' => $this->primaryKey(), 'photos' => $this->pivot('{{%photo}}')]);
```

Create a PivotTable by adding a column.

```
$this->addColumn('{{%user}}', 'photos', $this->pivot('{{%photo}}'));
```

Specify the name of the PivotTable

```
$this->addColumn('{{%user}}', 'photos', $this->pivot('{{%photo}}')->tableName('{{%album}}'));
```

PivotTrait
==========

[](#pivottrait)

Trait to help work with pivot tables.

`$company` - table model Company (requires trait PivotTrait)
`$user` - model of table User
`PvCompanyDirector` - a pivot table of the two models: company and user
`Pivot table` - a table which contains 2 primary key

Added to the table PvCompanyDirector a bunch of the end user company

```
$company->addPivot($user, PvCompanyDirector::class, $attributes = []);
```

Get the PvCompanyDirector model for the company-user bundle

```
$company->getPivot($model, PvCompanyDirector::class, $condition = []);
```

Removed a bunch of the user-company

```
$company->deletePivot($model, PvCompanyDirector::class);
```

Remove all users from PvCompanyDirector for this company

```
$company->deletePivots(PvCompanyDirector::class);
```

Save to a temporary link variable so that you can use them later

```
$company->storagePivot($user, PvCompanyDirector::class, ['hire_at' => '2010-01-01 00:00:00']);
$users = $company->getStoragePivots(PvCompanyDirector::class)); // The list of models that have been added earlier
```

The preservation of the ties of a temporary variable.
$clear - completely clears all links before adding

```
$company->savePivots($clear); // Save all links added via storagePivot
```

The change in behavior of the migration class
=============================================

[](#the-change-in-behavior-of-the-migration-class)

public function createIndex($name, $table, $columns, $unique = false)
---------------------------------------------------------------------

[](#public-function-createindexname-table-columns-unique--false)

- $name you can specify null to generate the index name automatically

public function createTable($table, $columns, $options = null)
--------------------------------------------------------------

[](#public-function-createtabletable-columns-options--null)

- $columns supports the $this-&gt;foreignKey() and $this-&gt;pivot()
- if $options is not specified, options are pulled from $this-&gt;tableOptions, if there are no options, then from **@tableOptions** to $columns

public function alterColumn($table, $column, $type)
---------------------------------------------------

[](#public-function-altercolumntable-column-type)

- $type supports type $this-&gt;foreignKey()

public function addColumn($table, $column, $type)
-------------------------------------------------

[](#public-function-addcolumntable-column-type)

- $type supports type $this-&gt;foreignKey() and $this-&gt;pivot()

public function addPrimaryKey($name, $table, $columns)
------------------------------------------------------

[](#public-function-addprimarykeyname-table-columns)

- $name you can specify null to generate the index name automatically

public function dropColumn($table, $column)
-------------------------------------------

[](#public-function-dropcolumntable-column)

- Before deleting the table, foreign keys are cleared

An example of a complete migration
==================================

[](#an-example-of-a-complete-migration)

```
