テーブル名をrenameした後、php artisan migrate:refresh系のコマンドをうったときに出るエラーを迅速に解決するには
php artisan migrate:refreshをすると、
英語のサイトを大量に巡回するハメになるような、エラーが出てくる場合があります。
巡回した方法を試しまくるうちに、これをしておけば、エラーが減るという注意点をまとめました。
チェックするポイント
マイグレーションファイルのdown関数内と、外部キー制約の部分をチェックします。
特に、renameしたときや、カラムをaddしたときのマイグレーションファイルを要チェックします。
例:favorite から favorites に変更した時
例えば、最初はfavoriteだったが、favoritesにするパターンで、
renameのとき、以下のように、downに何も書いてないパターン
<?php public function up() { Schema::rename('favorite', 'favorites'); } public function down() { }
migrate:refleshなどをすると、テーブルがないですよっというエラーが出る。
そりゃそうですね…。downにロールバック時の処理が書き忘れているから、ちゃんとロールバックできずに終わってしまいます。
down()に処理を書く
downにも名前を戻す処理を書いてあげます。
<?php public function down() { Schema::rename('favorites', 'favorite'); }
外部キー制約をつけている場合
さらに、favoriteの user_id と photo_id には外部キー制約を付けている場合は、
ここに、外部キーも、付け直す処理を入れてあげます。
<?php public function up() { //old_table Schema::table('favorite', function (Blueprint $table) { $table->dropForeign(['user_id']); $table->dropForeign(['photo_id']); }); Schema::rename('favorite', 'favorites'); //new_table Schema::table('favorites', function (Blueprint $table) { $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade'); $table->foreign('photo_id')->references('id')->on('photos')->onDelete('cascade'); }); } public function down() { //new_table Schema::table('favorites', function (Blueprint $table) { $table->dropForeign(['user_id']); $table->dropForeign(['photo_id']); }); Schema::rename('favorites', 'favorite'); //old_table Schema::table('favorite', function (Blueprint $table) { $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade'); $table->foreign('photo_id')->references('id')->on('photos')->onDelete('cascade'); }); }
以上でおしまい。
けっこうはまってしまったため、次からはこのポイントに注意していきたいと思います。