マイグレーションの作成・実行
Laravel勉強記録
実行環境
OS:Mac PHP:8.0 Laravel:8
マイグレーションとは
テーブルの定義をマネジメントするためのもの テーブルの作成・更新などをマイグレーションコマンドを用いて操作を行う
マイグレーションファイルの作成
マイグレーションファイルを作成
php artisan make:migration create_hoges_table --create=hoges
–create オプションでテーブル名 作成に成功するとこのようなログが出力される
Created Migration: 2020_06_24_055626_create_hoges_table
database/migrations/配下にファイルが作成される
ファイルの初期状態はこのような内容です
class CreateHogesTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('hoges', function (Blueprint $table) { $table->bigIncrements('id'); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('hoges'); } }
※upメソッド:マイグレーション時の動作を記載 downメソッド:ロールバック時の動作を記載
モデルとマイグレーションを一緒に作成
モデルとマイグレーションファイルを一緒に作成
php artisan make:model Hoge --migration
作成に成功すると以下ログが表示される
2020_09_01_092933_create_hoges_table.php
マイグレーションのコマンド
- マイグレーションの実行
php artisan migrate
- マイグレーションを戻す
php artisan migrate:rollback
- マイグレーションを全て戻す
php artisan migrate:reset
- マイグレーションを当て直す
php artisan migrate:refresh
- マイグレーション状態の確認
php artisan migrate:status
カラムを追加
- マイグレーションの作成
php artisan make:migration add_type_to_hoges_table --table=hoges
- マイグレーションファイル編集
class AddTypeToHogesTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::table('hoges', function (Blueprint $table) { $table->integer('type'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::table('hoges', function (Blueprint $table) { $table->dropColumn('type'); }); } }
- マイグレーションの実行
php artisan migrate
カラムの属性変更
- composerでライブラリ追加
composer require doctrine/dbal
- マイグレーション作成
php artisan make:migration change_type_to_hoges_table --table=hoges
- マイグレーションファイル修正
class ChangeTypeToHogesTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::table('hoges', function (Blueprint $table) { $table->string('type')->change(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::table('hoges', function (Blueprint $table) { $table->integer('type')->change(); }); } }
- マイグレーション実行
php artisan migrate
ひとつ前にロールバック
php artisan migrate:rollback --step 1