1
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

CakePHP3でMigration Pluginを使用してテーブルを作成する

1
Last updated at Posted at 2019-09-10

この記事について

この記事ではCakePHPのPluginであるMigrationの初期設定方法を紹介する。

モチベーション

複数マシンを使用し開発を行う場合、もちろんDBにあるスキーマ、テーブルも同じモノであった方がいい。以下のようなDDLをチームで共有してもさほど問題はないかもしれないが、テーブル定義が変更したりする際、わざわざMySQLWorkbenchなどのRDMS管理ツールでSQLを叩かなくてはいけなくてめんどくさい。今回紹介するMigrationであれば、CakePHP内のファイルを編集するだけでテーブル情報も自然に更新されるため、作業効率を高め、無駄なDB作業を減らすことができる。


CREATE TABLE topics (
id INT AUTO_INCREMENT PRIMARY KEY,
user_id INT NOT NULL,
name VARCHAR(255),
description TEXT
);

手順

以下を参考にしました。
CakePHP公式:https://book.cakephp.org/3.0/en/plugins.html
CakePHP3のマイグレーションでデータベースを構築する: https://www.ritolab.com/entry/60

下準備

前記事の下準備と同様。

Migrationのロードの仕方

CakePHPではPluginと呼ばれるツールを用意している。このPluginを読み込むには、src/Application.phpの'bootstrap()'メゾット内に$this->addPlugin('Migrations');と記述する。Defaultで既にこのコードがある場合は、記述があることを確認するだけで良い。

    public function bootstrap()
    {
        // Call parent to load bootstrap from files.
        parent::bootstrap();

        if (PHP_SAPI === 'cli') {
            $this->bootstrapCli();
        }

        /*
         * Only try to load DebugKit in development mode
         * Debug Kit should not be installed on a production system
         */
        if (Configure::read('debug')) {
            $this->addPlugin(\DebugKit\Plugin::class);
        }

        // Migrationを追加
        $this->addPlugin('Migrations');
    }

MigrationsフォルダとInitialファイルの作成

cakephpルートディレクトリへ移動し、以下のコマンドを実行。

bin/cake bake migration_snapshot Initial

※実行結果のデモ
migration_1_demo.gif

これにより、configフォルダ配下にMigrationsというフォルダと、その下に(現在時間)_Initial.phpというファイルが作成される。
自分の場合、20190910033843_Initial.phpが作成された。

ユーザーテーブルの作成

cakephpルートディレクトリへ移動し、'users'テーブルを作成するため、以下のコマンドを実行。

bin/cake bake migration CreateUsers name:string password:string role:integer[1]:indexType:indexRole last_login_at created modified

これにより、Migrations配下に(現在時間)_CreateUsers.phpというファイルが作成される。
ちなみに、(現在時間)_CreateUsers.phpの内容は以下のようになっている。

<?php
use Migrations\AbstractMigration;

class CreateUsers 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('users');
        $table->addColumn('name', 'string', [
            'default' => null,
            'limit' => 255,
            'null' => false,
        ]);
        $table->addColumn('password', 'string', [
            'default' => null,
            'limit' => 255,
            'null' => false,
        ]);
        $table->addColumn('role', 'integer', [
            'default' => null,
            'limit' => 1,
            'null' => false,
        ]);
        $table->addColumn('last_login_at', 'datetime', [
            'default' => null,
            'null' => false,
        ]);
        $table->addColumn('created', 'datetime', [
            'default' => null,
            'null' => false,
        ]);
        $table->addColumn('modified', 'datetime', [
            'default' => null,
            'null' => false,
        ]);
        $table->addIndex([
            'role',
        ], [
            'name' => 'indexRole',
            'unique' => false,
        ]);
        $table->create();
    }
}

マイグレーション実行

cakephpルートディレクトリへ再度移動し、以下のコマンドを実行。

bin/cake migrations migrate

※実行結果
image.png
successfully writtenとあるのでマイグレーションが成功したよう。

MySQLWorkbenchでDBに接続し、usersテーブルが作成されていることも以下のように確認できる。
image.png

最後に

この記事ではCakePHPのPluginであるMigrationについて紹介しました。
つまづいたり、わからないことがあれば、気軽にコメントください。

1
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?