5
2

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 3 years have passed since last update.

Laravel Migration - Enum型カラムのオプションの変更方法

Last updated at Posted at 2021-04-05

実現したいこと

実現したいことは、Enum型カラムのオプションを変更することです。

例)
変更前のusersテーブル

Field Type Length
id BIGINT 20
name VARCHAR 255
type ENUM 'member','cancel'

変更後のusersテーブル

Field Type Length
id BIGINT 20
name VARCHAR 255
type ENUM 'member','cancel','recess'

ENUM型のtypeカラムのオプションはmember(会員)、cancel(退会)が存在します。このオプションにrecess(休会)を追加したいと思います。

実現方法

*私のLaravelのバージョンは5.8.36です。

変更用のマイグレーションファイルを作成します。

$ php artisan make:migration change_column_type_users_table --table=users

作成されたマイグレーションファイルを下記のように記述します。

database/migrations/2021_04_05_183257_change_column_type_users_table.php
<?php

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

class ChangeColumnTypeUsersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        DB::statement("ALTER TABLE users MODIFY type ENUM ('member', 'cancel', 'recess')");
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        DB::statement("ALTER TABLE users MODIFY type ENUM ('member', 'cancel')");
    }
}

マイグレーション実行

$ php artisan migrate

以上です。
ちなみに下記のような記述では変更できません。理由は、DBAL 2.9.2は列挙型データ型をサポートしていないからだそうです。

Schema::table('users', function (Blueprint $table) { 
    $table->enum('type', ['member', 'cancel', 'recess'])->change(); 
});

参考

5
2
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
5
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?