LoginSignup
0
0

More than 1 year has passed since last update.

DBのテーブルをmigrationファイルで削除する方法

Posted at

実務の中で、仕様が途中で変更になり開発環境で作成したDBのテーブルを削除する必要があり
その際の対応を学習のためにメモで残したものになります。

ローカル環境で、不要なテーブルを削除する場合は、以下のコマンドなどで削除することが出来る。

php artisan migrate:refresh

しかし、このコマンドではデータが削除されてしまうため、
開発環境や本番環境にすでに上げてしまったテーブルには、使用することが出来ない。

その場合は、migrationファイルを新たに作成し、削除を行う必要がある。

以下の手順がその対応になります。

まず、以下のコマンドでmigrationファイルを作成します。

php artisan make:migration drop_users_table

ファイル名は任意の名前で問題ありません。
(他の人が何のファイルか理解できる、またはプロジェクトの命名規則に従う)

<?php

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

class CreateUsersTable extends Migration
{

    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        /**
         * ここにテーブルの削除処理を記述
         * drop でも削除できるが、 dropIfExistsを使用した方が良い
         * 理由は、dropIfExistsであれば、テーブルが存在する場合に実行されるので、
         * 環境によってテーブルの有無でエラーを引き起こす可能性がなくなるため
         */
        Schema::dropIfExists('users');
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        /**
         * 処理が上手くいかない場合に備えて必ず記述する必要がある
         * ここには、テーブルの作成時と同じ処理を記述する
         */
        Schema::create('users', function (Blueprint $table) {
            $table->increments('id');
            $table->timestamps();
        });
    }
}

あとは、このmigrationファイルを実行することで、
開発環境や本番環境のテーブルを削除できます。

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