composer require doctrine/dbal
Laravelのマイグレーションでカラムの名前と型を変更するには、
今既にあるマイグレーションファイルは 変更せずに置いておいて、変更を記述したマイグレーションファイルを新規に作成します。
テーブル名 | カラム名 | 型 |
---|---|---|
artists | year_birth_no | smallint |
↓ (例)こちらに変更するとします。
テーブル名 | カラム名 | 型 |
---|---|---|
artists | year_birth_no_name | string |
マイグレーションファイル名はなんでもいいです。
php artisan make:migration change_artists_table_column_year_birth_no --table=artists
成功すると 次のようなファイルが生成されます
2019_07_08_180737_change_artists_table_column_year_birth_no
以下のように変更用の命令と戻し用の命令を記述しておきます。
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class ChangeArtistsTableColumnYearBirthNo extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
// カラム名を変更
Schema::table('artists', function (Blueprint $table) {
$table->renameColumn('year_birth_no', 'year_birth_no_name');
});
// 型を変更
Schema::table('artists', function (Blueprint $table) {
$table->string('year_birth_no_name')->default(NULL)->change();
});
// カラム「fax_name」を「string型」「nullを許可」に変更
$table->string('fax_name')->nullable()->change();
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
// 型を戻す
Schema::table('artists', function (Blueprint $table) {
$table->smallInteger('year_birth_no_name')->change();
});
// カラム名を戻す
Schema::table('artists', function (Blueprint $table) {
$table->renameColumn('year_birth_no_name','year_birth_no');
});
// カラム「fax_name」を「string型」「nullを許可しない」に変更
$table->string('fax_name')->nullable(false)->change();
}
}
(注意)tinyIntegerでは実行できません。 ↓ を参照
composer require doctrine/dbal
php artisan migrate
php artisan migrate:rollback
composer require "doctrine/dbal:2.*"
Schema::table('applications', function (Blueprint $table) {
// nullを許可に変更
DB::statement('ALTER TABLE users MODIFY COLUMN is_active tinyint COMMENT \'フラグ\'');
});