[Laravel] tinyint型のカラムをマイグレーションで変更する方法

スポンサーリンク

概要

Laravel 10までのマイグレーションでは、tinyint型のカラムをchangeメソッドで変更しようとすると以下のエラーとなりうまくいかない。
Unknown column type “tinyinteger” requested.

マニュアルに以下の記述があるように、マイグレーションで変更できるデータ型は限られている。

When using the doctrine/dbal package, the following column types can be modified: bigInteger, binary, boolean, char, date, dateTime, dateTimeTz, decimal, double, integer, json, longText, mediumText, smallInteger, string, text, time, tinyText, unsignedBigInteger, unsignedInteger, unsignedSmallInteger, ulid, and uuid.

Laravel - The PHP Framework For Web Artisans
Laravel is a PHP web application framework with expressive, elegant syntax. We’ve already laid the foundation — freeing you to create without sweating the small things.

解決方法

DBファサードを使ってALTER TABLE文を実行する。

デフォルト値を0から1にする例

public function up()
{
    Schema::table('items', function (Blueprint $table) {
        DB::statement('alter table items change column amount amount tinyint default 1');
    });
}

public function down()
{
    Schema::table('items', function (Blueprint $table) {
        DB::statement('alter table items change column amount amount tinyint default 0');
    });
}

tinyint型をint型にする例

public function up()
{
    Schema::table('items', function (Blueprint $table) {
        $table->integer('amount')->default(0)->change();
    });
}

public function down()
{
    Schema::table('items', function (Blueprint $table) {
        DB::statement('alter table items change column amount amount tinyint default 0');
    });
}

おすすめ書籍

コメント