![](https://i0.wp.com/system-sutaruhin.com/wp-content/uploads/2020/04/0-06-2.jpg?w=1256&ssl=1)
新規テーブル時の外部キー作成は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なので戻るも先へも行けなくなります
![](https://i0.wp.com/image.moshimo.com/af-img/1548/000000030527.png?resize=468%2C60)
対策
(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');
});
}
![](https://i0.wp.com/system-sutaruhin.com/wp-content/uploads/2020/04/04-3.jpg?w=1256&ssl=1)
![](https://i0.wp.com/image.moshimo.com/af-img/2596/000000042364.jpg?resize=200%2C200)