【Laravel】マイグレーションの使い方
新規作成
1. モデルとマイグレーション作成
php artisan make:model <ModelName> --migration
2. マイグレーション編集
以下のようなファイルが作成されるため、必要な項目を追記する。
20xx_xx_xx_xxxxxx_create<model-names>table.php
例えば、hellosテーブルを作成し、id/created_at/updated_atのカラムを用意する場合
public function up() { Schema::create('hellos', function (Blueprint $table) { $table->bigIncrements('id'); $table->timestamps(); }); } public function down() { Schema::dropIfExists('hellos'); }
3. 反映
php artisan migrate
変更
0. パッケージを追加(初回のみ)
composer require doctrine/dbal
1. マイグレーション作成
モデルは作成済みのため、マイグレーションのみ作成
php artisan make:migration <migration_name> --table=<table_name>
2. マイグレーション編集
生成された以下のようなファイルを編集。
20xx_xx_xx_xxxxxx_<migration_name>.php
変更の場合はSchema::createではなく、Schema::table。
Schema::table('table_name', function(Blueprint $table){ //... });
例として、idのあとにnameのカラムを追加する場合。
$table->string('name')->default('')->after('id');
ただし、afterはMySQLのみ
戻す場合は追加したカラムを削除します。
$table->dropColumn('name');
3. 反映
php artisan migrate
取り消し
migrateを一つ戻す
php artisan migrate:rollback