删除 laravel 中的无符号索引外键。语法错误或访问冲突:1091 Can't DROP;检查 column/key 是否存在

Dropping unsigned index foreign key in laravel. Syntax error or access violation: 1091 Can't DROP; check that column/key exists

我使用以下方法创建了迁移

Schema::table('packages', function (Blueprint $table) {
     $table->integer('star_id')->unsigned()->index()->nullable()->default(null);
     $table->foreign('star_id')->references('id')->on('star');
});

掉落部分

Schema::table('packages', function (Blueprint $table) {
      $table->dropForeign('star_id');
      //$table->dropIndex('star_id'); //also tried dropIndex
      $table->dropColumn('star_id');
 });

但它会抛出索引和外部

SQLSTATE[HY000]: General error: 1553 Cannot drop index 'packages_star_id_index': needed in a foreign key constraint (SQL: alter table packages drop star_id)

dropForeign 错误

SQLSTATE[42000]: Syntax error or access violation: 1091 Can't DROP 'star_id'; check that column/key exists (SQL: alter table packages drop foreign key star_id)

我因为错误无法回滚。

您必须自己传递外键名称或传递数组中的列名称,laravel 才能自动构建它。

参见here

If the given "index" is actually an array of columns, the developer means to drop an index merely by specifying the columns involved without the conventional name, so we will build the index name from the columns.

// laravel assumes star_id is the foreign key name
$table->dropForeign('star_id'); 

// laravel builds the foreign key name itself e.g. packages_star_id_foreign
$table->dropForeign(['star_id']);

因此,在您的情况下,只需传递数组中的列即可:

Schema::table('packages', function (Blueprint $table) {
    $table->dropForeign(['star_id']);
    $table->dropColumn('star_id');
});

基于 Laravel 7 文档,用于删除外键 此代码将起作用:

$table->dropForeign('posts_user_id_foreign');

其中"posts"是table名称,"user_id"是外键名称,"foreign"是后缀。

还有另一种方法只传递数组中的外键名称,如下所示:

$table->dropForeign(['user_id']);

此图来自Laravel网站(v7.x): here

Blockquote SQLSTATE[HY000]: General error: 1553 Cannot drop index 'packages_star_id_index': needed in a foreign key constraint (SQL: alter table packages drop star_id)

根据您的错误,索引名称是“packages_star_id_index”。 您应该在 dropForeign 函数中提及正确的索引名称。

试一试:

Schema::table('packages', function (Blueprint $table) {
      $table->dropForeign('packages_star_id_index');
      $table->dropColumn('star_id');
 });