
新規テーブル時の外部キー作成はOK
public function up()
{
Schema::create('categorys', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id')->unsigned()->index();
$table->string('content');
$table->timestamps();
// 外部キー制約
$table->foreign('user_id')->references('id')->on('users');
});
}
public function down()
{
Schema::dropIfExists('categorys');
}
カラム追加ではマイグレーションのデッドロックになりやすい
public function up()
{
Schema::table('categorys', function (Blueprint $table) {
$table->string('bunrui_cd')->unsigned()->index();
// 外部キー制約
$table->foreign('bunrui_cd')->references('id')->on('bunruis');
});
}
public function down()
{
Schema::table('categorys', function (Blueprint $table) {
$table->dropColumn('bunrui_cd');
});
}
この場合、既存データが存在している場合、bunrui_cdは作成済みで外部キー作成でエラーとなります。マイグレーションはNなので戻るも先へも行けなくなります

対策
(1)カラムと外部キー作成のマイグレーションを分離する
(2)down には外部キー削除をカラム追加の後に行う
public function down()
{
Schema::table('categorys', function (Blueprint $table) {
$table->dropColumn('bunrui_cd');
// $table->dropForeign('[テーブル名]_[フォーリンキーを取り除くカラム名]_foreign');
$table->dropForeign('categorys_bunrui_cd_foreign');
});
}

