概要
dropForeignメソッドの引数はカラム名ではない!
他のカラムを設定するメソッドのincrementsメソッドやintegerメソッドと同様にそのテーブルを指した状態でカラム名を指定してあげればdropForeignが正しく実行できると勘違いしていました。
実行
下記のようなデータ構造で、マイグレーションを実行すると外部キーが除外され、ロールバックで再度、外部キーが設定されるようにしてみました。
- テーブル名:books
- カラム名:category
- 外部キー設定先テーブル名:book_categories
- 外部キー設定先カラム名:id
public function up()
{
Schema::table('books', function (Blueprint $table) {
$table->dropForeign('category');
});
}
public function down()
{
Schema::table('books', function (Blueprint $table) {
$table->foreign('category')->references('id')->on('book_categories');
});
}
エラー
上記のマイグレーションを実行すると以下のエラーが発生します。
[Illuminate\Database\QueryException]
SQLSTATE[HY000]: General error: 1025 Error on rename of './test/books' to './test/#sql2-102f-174' (errno: 152) (SQL: alter table `books`
drop foreign key `category`)
[PDOException]
SQLSTATE[HY000]: General error: 1025 Error on rename of './test/books' to './co_tech/#sql2-102f-174' (errno: 152)
修正
原因としてはフォーリンキーの指定がいけないようです。
$table->dropForeign('[テーブル名]_[フォーリンキーを取り除くカラム名]_foreign');
上記の通り、dropForeignの引数には、[テーブル名]_[フォーリンキーを取り除くカラム名]_foreignという形になります。
最終的に下記のような形で実行できました。
public function up()
{
Schema::table('books', function (Blueprint $table) {
$table->dropForeign('books_category_foreign');
});
}
public function down()
{
Schema::table('books', function (Blueprint $table) {
$table->foreign('category')->references('id')->on('book_categories');
});
}
これでまたマイグレーションで幸せに!