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?

既存テーブルへのカラム追加

Posted at

はじめに

とあるプロジェクトでテーブルへのカラム追加をしようとした時に、既に作成されていたテーブルのマイグレーションファイルを書き換えて追加しようとしてしまったので、今後同じミスをしないように書き留めておこうと思います。

使用環境→Laravel:mysql

問題点

既にあるテーブルを書き換えると、php artisan migrateの対象にならなかったり、Laravelが知らないうちに書き換わることで不都合が生じてしまうようです。

テーブルへのカラム追加

まず、代替となるマイグレーションファイル「alter」を作成します。
1行目はdocker環境を使用しているためphpコンテナにアクセスしています。2行目は既存のテーブル「sample_files」を対象としたファイル、「alter_sample_files」を作成するコマンドです。

docker compose exec php bash
php artisan make:migration alter_sample_files --table=sample_files

作成されたマイグレーションファイルを編集していきます。
upとdownのそれぞれに、今回追加したいカラムである「folder_id」と「member_id」を追加します。

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::table('sample_files', function (Blueprint $table) {
            $table->after('key', function($table){
                $table->unsignedInteger('folder_id')->nullable()->comment('フォルダID');
                $table->unsignedInteger('member_id')->nullable()->comment('会員ID');
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::table('sample_files', function (Blueprint $table) {
            $table->dropColumn('folder_id');
            $table->dropColumn('member_id');
        });
    }
};

確認

次のように、マイグレーションを実行して作成したテーブルを反映させます。成功すれば、テーブルにカラムが追加されているはずです(php my admin等で確認)。

php artisan migrate

念のため、一度ロールバックして期待通り元に戻るか確認

 php artisan migrate:rollback --step=1

終わりに

DB操作はそこまで詳しくないですが、間違った方法で行ってしまうと面倒な事態に発展してしまうと思います。
不慣れな操作を行うときは、それがどういうことなのかしっかり理解してから行うように心がけたいです。

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?