web学習日記

プログラミングやweb関係を学んだことを呟くブログ

CakePHPのマイグレーションについて

f:id:nana205:20190614011943j:plain
PHPフレームワークマイグレーションの機能がついています。データーベスの構築をコードで管理することができ、
コーディングした時に テーブルやカラムの追加、変更に必要になった時にコマンド一発で構築できる優れものです。
Laravelなどの他のフレームワークなどにもあります。

目次

1.開発環境

2.マイグレーションでテーブルを構築する
01.マイグレーションファイルの作成
02.マイグレーションの実行
3.マイグレーションでカラムを追加する   
01.マイグレーションファイルの作成
02.マイグレーションの実行
4.マイグレーションでカラムを変更する   
01.マイグレーションファイルの作成
02.マイグレーションの実行
5.マイグレーションでカラムを削除する   
01.マイグレーションファイルの作成
02.マイグレーションの実行
6.ロールバックの実行

7.マイグレーションのステータス確認

開発環境

・Docker
・DockerCompose
・PHP7.2
・MySQL5.7
・CakePHP3.8

マイグレーションでテーブルを構築する

マイグレーションファイルの作成

# bakeコマンドでsamplesテーブル構築のマイグレーションファイルを生成する
bin/cake bake migration CreateSamples name:string
cakephp/config/Migrations/XXXX_CreateSamples.php
<?php
use Migrations\AbstractMigration;

class CreateSamples extends AbstractMigration
{
    public function change()
    {
        $table = $this->table('samples');
        $table->addColumn('name', 'string', [
            'default' => null,
            'limit' => 255,
            'null' => false,
        ]);
        $table->create();
    }
 }
}

マイグレーションを実行する

bin/cake migrations migrate

MySQLにログインしてテーブルが作成されているか確認する

mysql> tables;
+-------------------+
| Tables_in_cakephp |
+-------------------+
| phinxlog          |
| samples           |
+------------------+

これでテーブルが構築されました。

マイグレーションでカラムを追加する

マイグレーションのカラム操作をします。

マイグレーションファイルの作成

最初にマイグレーションファイルを生成するが、一定の書式がある

bin/cake bake migration AddAgeToSamples age:integer?[3]

クラス名を「Add[カラム名]To[テーブル名]」とし、
その後に追加カラム情報を記述する事で、カラム追加のマイグレーションファイルが生成されます。

AddAgeToSamples

意味:ageカラムをsampleカラムに追加

age:integer?[3]

意味:ageカラムはint型 NULLを許容して、最大文字長3文字とする。 任意のディレクトリに移動して以下のコマンドを追加する

# bakeコマンドでageカラムをsamplesテーブルに追加するマイグレーションファイルを生成する
bin/cake bake migration AddAgeToSamples age:integer?[3]
cakephp/config/Migrations/XXXX_AddAgeToSamples.php
<?php
use Migrations\AbstractMigration;

class AddAgeToSamples extends AbstractMigration
{
    /**
     * Change Method.
     *
     * More information on this method is available here:
     * http://docs.phinx.org/en/latest/migrations.html#the-change-method
     * @return void
     */
    public function change()
    {
        $table = $this->table('samples');
        $table->addColumn('age', 'integer', [
            'default' => null,
            'limit' => 3,
            'null' => true,
        ]);
        $table->update();
    }
}

sampleテーブルにageカラムをaddColumn()するクラスが生成されました。
しかし、ここで問題があり、自動生成されたメソッドはchange()メソッドで実装されていて、このままではロールバックの時にエラーになりロールバックができなくなるので、up()down()メソッドに実装し直します。

<?php
use Migrations\AbstractMigration;

class AddAgeToSamples extends AbstractMigration
{
    /**
     * Change Method.
     *
     * More information on this method is available here:
     * http://docs.phinx.org/en/latest/migrations.html#the-change-method
     * @return void
     */
    public function up()
    {
        $table = $this->table('samples');
        $table->addColumn('age', 'integer', [
            'default' => null,
            'limit' => 3,
            'null' => true,
        ]);
        $table->update();
    }

    public function down()
    {
      $table = $this->table('samples');
      $table->removeColumn('age');
      $table->update();
    }
}

up()メソッドはマイグレーション時に実行されるメソッド、down()メソッドはロールバック時に実行されるメソッドです。
この場合では、マイグレーション時にはageカラムの追加を行いますが、down()メソッドではageカラムを削除します。

マイグレーションの実行

マイグレーションを実行し、samplesテーブルにaddカラムを追加します。

マイグレーションを実行する

bin/cake migrations migrate

MySQLへログインし、samplesテーブルに ageカラムが追加されているか確認します。

mysql> show columns from samples;
+-------+--------------+------+-----+---------+----------------+
| Field | Type         | Null | Key | Default | Extra          |
+-------+--------------+------+-----+---------+----------------+
| id    | int(11)      | NO   | PRI | NULL    | auto_increment |
| name  | varchar(255) | NO   |     | NULL    |                |
| age   | int(3)       | YES  |     | NULL    |                |
+-------+--------------+------+-----+---------+----------------+

マイグレーションカラムの変更

マイグレーションファイルの作成

bin/cake bake migration ChangeAgeToSamples

追加した時と同じような命名規則にしておくとわかりやすいです。 コマンドを叩きます。

bin/cake bake migration ChangeAgeToSamples
cakephp/config/Migrations/XXXX_ChangeAgeToSamples.php
<?php
use Migrations\AbstractMigration;

class ChangeAgeToSamples extends AbstractMigration
{
    /**
     * Change Method.
     *
     * More information on this method is available here:
     * http://docs.phinx.org/en/latest/migrations.html#the-change-method
     * @return void
     */
    public function change()
    {
    }
}

カラムの変更を記述する

<?php
use Migrations\AbstractMigration;

class ChangeAgeToSamples extends AbstractMigration
{
    /**
     * Change Method.
     *
     * More information on this method is available here:
     * http://docs.phinx.org/en/latest/migrations.html#the-change-method
     * @return void
     */
    public function change()
    {
      $table = $this->table('samples');
      $table->changeColumn('age', 'integer', [
        'limit' => 2,
      ]);
      $table->update();
    }
}

changeColumn()メソッドを用いているところがポイント、そして、change()メソッドをup()down()メソッドに変更する

?php
use Migrations\AbstractMigration;

class ChangeAgeToSamples extends AbstractMigration
{
    /**
     * Change Method.
     *
     * More information on this method is available here:
     * http://docs.phinx.org/en/latest/migrations.html#the-change-method
     * @return void
     */
    public function up()
    {
      $table = $this->table('samples');
      $table->changeColumn('age', 'integer', [
        'limit' => 2,
      ]);
      $table->update();
    }

    public function down()
    {
      $table = $this->table('samples');
      $table->changeColumn('age', 'integer', [
        'limit' => 3,
      ]);
      $table->update();
    }
}

マイグレーションの実行

bin/cake migrations migrate

MySQLへログインし、ageカラムが変更されているか確認します。

mysql> show columns from samples;
+-------+--------------+------+-----+---------+----------------+
| Field | Type         | Null | Key | Default | Extra          |
+-------+--------------+------+-----+---------+----------------+
| id    | int(11)      | NO   | PRI | NULL    | auto_increment |
| name  | varchar(255) | NO   |     | NULL    |                |
| age   | int(2)       | NO   |     | NULL    |                |
+-------+--------------+------+-----+---------+----------------+

マイグレーションでカラムを削除する

マイグレーションファイルの作成

bin/cake bake migration RemoveAgeFromSamples age

クラス名を「Remove[カラム名]To[テーブル名]」とし、その後に削除対象のカラム名を記述する事で、
カラム削除のマイグレーションファイルが生成されます。

RemoveAgeFromSamples

意味:samplesテーブルのageカラムを削除する

age

意味:削除対象のカラム名

コマンドを叩きます

bin/cake bake migration RemoveAgeFromSamples age
cakephp/config/Migrations/XXXX_RemoveAgeFromSamples.php
?php
use Migrations\AbstractMigration;

class RemoveAgeFromSamples extends AbstractMigration
{
    /**
     * Change Method.
     *
     * More information on this method is available here:
     * http://docs.phinx.org/en/latest/migrations.html#the-change-method
     * @return void
     */
    public function change()
    {
        $table = $this->table('samples');
        $table->removeColumn('age');
        $table->update();
    }
}

これもup()down()メソッドに変える

<?php
use Migrations\AbstractMigration;

class RemoveAgeFromSamples extends AbstractMigration
{
    /**
     * Change Method.
     *
     * More information on this method is available here:
     * http://docs.phinx.org/en/latest/migrations.html#the-change-method
     * @return void
     */
    public function up()
    {
        $table = $this->table('samples');
        $table->removeColumn('age');
        $table->update();
    }

    public function down()
    {
      $table = $this->table('samples');
      $table->addColumn('age', 'integer', [
        'default' => null,
        'limit' => 2,
        'null' => true,
      ]);
      $table->update();
    }
}

マイグレーションの実行

# マイグレーションを実行する
bin/cake migrations migrate

MySQLへログインし、ageカラムが削除されているか確認します。

mysql> show columns from samples;
+-------+--------------+------+-----+---------+----------------+
| Field | Type         | Null | Key | Default | Extra          |
+-------+--------------+------+-----+---------+----------------+
| id    | int(11)      | NO   | PRI | NULL    | auto_increment |
| name  | varchar(255) | NO   |     | NULL    |                |
+-------+--------------+------+-----+---------+----------------+

削除されていることが確認できます。

まとめ

以上でマイグレーション作成は終わります。 このようにマイグレーションでデータベースを管理すると、テーブルやカラムの変更が容易にできます。 MySQLにログインしなくてもCakePHPのソースでテーブル内容が確認できるのは便利ですね。ぜひ利用してみてください。