Laravel迁移中删除外键

15

我想创建一个迁移,以删除一张表。我创建了以下迁移:

Schema::table('devices', function (Blueprint $table) {
    $table->increments('id');
    $table->unsignedInteger('client_id')->nullable();
    $table->foreign('client_id')->references('id')->on('clients')->onDelete('cascade');
});

现在我尝试这样删除它:

    Schema::table('devices', function (Blueprint $table) {
        $table->dropForeign('devices_client_id_foreign');
        $table->drop('devices');
    });

但我收到以下错误信息:
In Connection.php line 664:

  SQLSTATE[42000]: Syntax error or access violation: 1091 Can't DROP 'devices_client_id_foreign'; check that column/key exists (SQL:

alter table devices drop foreign key devices_client_id_foreign)

In PDOStatement.php line 144:

  SQLSTATE[42000]: Syntax error or access violation: 1091 Can't DROP 'devices_client_id_foreign'; check that column/key exists


In PDOStatement.php line 142:

  SQLSTATE[42000]: Syntax error or access violation: 1091 Can't DROP 'devices_client_id_foreign'; check that column/key exists
4个回答

32

当您没有为它指定不同于Laravel默认设置的FK名称时,此方法可以正常工作。 - Daniel Hernández

7

尝试以下方法...

  public function down()
 {
    Schema::dropIfExists('devices');
 }

//Or this
  public function down(){
    Schema::table('devices', function (Blueprint $table) {
        $table->dropForeign(['client_id']);
        $table->dropColumn('client_id');
        $table->drop('devices');
    });
  }

有一个外键,我不能那么轻易地删除它。 - Jon not doe xx

7

在删除表之前,您只需要禁用外键检查,然后再像这样重新启用它们:

DB::statement('SET FOREIGN_KEY_CHECKS=0;');
Schema::dropIfExists('devices');
DB::statement('SET FOREIGN_KEY_CHECKS=1;');

如果创建一个迁移,添加和删除特定的列,这是行不通的。例如,如果你正在向用户表中添加一列,这个命令会删除整个用户表,可能会造成灾难性的后果。最好在down函数中使用@laurazel8的回答。 - DeveloperChris
如果创建一个迁移,添加和删除特定的列,这是行不通的。例如,如果你正在向用户表中添加一列,这个命令会删除整个用户表,这可能是灾难性的。最好在down函数中使用@laurazel8的回答。 - undefined

-1

只需删除整个表格(文档):

Schema::drop('devices');

嗨,这里有一个外键Client_id,所以我不能轻易删除它。 - Jon not doe xx
Integrity constraint violation: 1217 Cannot delete or update a parent row: a foreign key constraint fails (SQL: drop table devices) - Jon not doe xx
其他表中是否有外键引用了“devices”表? - Jonas Staudenmeir
为什么在 down 方法中删除整个表,而在 up 方法中不创建表? - Sizzling Code
2
当表中存在外键时,您无法删除整个表。 - shamaseen

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接