0
0

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 1 year has passed since last update.

Laravelマイグレーション整理

Posted at

はじめに

Laravelを使用し、マイグレーション機能を使用してテーブルを作る時、マイグレーションファイルについて整理した。

テーブル作成時、以下のようなマイグレーションファイルを結果作成したので、それを元に記載する。
/Applications/MAMP/htdocs/work_flow/database/migrations
今回はMAMPを使用している。

.
├── 2014_10_12_000000_create_users_table.php
├── 2014_10_12_100000_create_password_reset_tokens_table.php
├── 2019_08_19_000000_create_failed_jobs_table.php
├── 2019_12_14_000001_create_personal_access_tokens_table.php
├── 2023_08_06_031748_create_projects_table.php
├── 2023_08_06_032207_create_project_user_table.php
├── 2023_08_06_032630_create_tasks_table.php
├── 2023_08_06_070530_add_user_id_to_projects_table.php
├── 2023_08_06_073841_add_completed_to_tasks_table.php
├── 2023_08_06_074451_add_default_value_to_status_in_tasks_table.php
└── 2023_08_06_074943_add_status_to_tasks_table.php

マイグレーションファイル

2023_08_06_031748_create_projects_table.phpは以下を実行している

php artisan make:migration create_projects_table

2023_08_06_074943_add_status_to_tasks_table.phpは以下を実行している

php artisan make:migration add_status_to_tasks_table --table=tasks

2023_08_06_031748は実行した時のタイムスタンプである。

--table=tasksはテーブル名を間違いなく記載するオプション。

createとかaddとか特定のキーワードに対し特別な動作をするのではなく慣習的なものである。
命名規則として使用されている。

createが名前に含まれる場合、新しいテーブルを作成するためのマイグレーションが期待される。試したところ、down()にはSchema::dropIfExists('テーブル名')が記載されている。(つまりcreateで一応判断はしていると思う、バージョンによって確認要)

addが名前に含まれる場合、既存のテーブルにカラムを追加するためのマイグレーションが期待される。実際はファイルに手動でカラムを追加する。

マイグレーションの処理方法

処理を1つ戻す、複数回戻す、データを取り直す場ありを例に挙げる。

・php artisan migrate:rollback
最後に実行されたバッチのマイグレーションをロールバックする。
この例では、日付が最も遅い2023_08_06_074943_add_status_to_tasks_table.phpがロールバックされる。

・php artisan migrate:rollback --step=3
最後に実行された3バッチのマイグレーションをロールバックする。
この例では、以下がロールバックされる
2023_08_06_073841_add_completed_to_tasks_table.php
2023_08_06_074451_add_default_value_to_status_in_tasks_table.php
2023_08_06_074943_add_status_to_tasks_table.php

・php artisan migrate:fresh --seed
このコマンドは、データベース内の全テーブルをドロップし、マイグレーションを最初から実行し直す。さらに、--seedオプションが付いているため、全マイグレーションが完了した後に、データベースシーダーが実行されます。通常、DatabaseSeeder.phpファイルに定義されたシーダーが実行される。--seedがなければデーターベースシーダーが実行されないだけである。

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

先ほども述べたようにmigrateの記載に関わらず、大体同じものができる。
いずれのマイグレーションを実行しても大体変更前の記載になる。

今回色々マイグレーションファイルを作っているが、マイグレーションで追加したりしたものを1つにまとめた例を挙げる。
1.マイグレーションファイル作成
2.カラム、外部キー追加
3.マイグレーションファイルを1つにする。

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

    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::create('projects', function (Blueprint $table) {
            $table->id();
            $table->string('title');
            $table->text('description')->nullable();
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::dropIfExists('projects');
    }

2.カラム、外部キー追加
php artisan make:migration add_user_id_to_projects_table --table=projects
(作成時)

    public function up(): void
    {
        Schema::table('tasks', function (Blueprint $table) {
            //
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::table('tasks', function (Blueprint $table) {
            //
        });
    }

(カラム追加後)


    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::table('projects', function (Blueprint $table) {
            //
            $table->unsignedBigInteger('user_id')->after('id');

            $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::table('projects', function (Blueprint $table) {
            //
            $table->dropForeign(['user_id']);
            $table->dropColumn('user_id');
        });
    }

3.マイグレーションファイルを1つにする。
1.2は最初から以下と同じこと

    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::create('projects', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('user_id');
            $table->string('title');
            $table->text('description')->nullable();
            $table->timestamps();

            $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');

    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::dropIfExists('projects');
    }

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?