Laravel在迁移中删除外键

10 浏览
0 Comments

Laravel在迁移中删除外键

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

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

0
0 Comments

问题:Laravel在迁移中删除外键的原因是什么以及解决方法是什么?

原因:由于Laravel默认设置了外键的名称,所以在迁移中删除外键时,需要使用默认的外键名称。

解决方法:可以使用以下方法来删除外键:

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

参考链接:https://stackoverflow.com/a/30177480/8513937

0
0 Comments

问题原因:有一个外键无法轻易删除。

解决方法:尝试以下两种方法:

方法一:

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

方法二:

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

0
0 Comments

在Laravel中,如果我们想要删除一个表的外键,我们需要在删除表之前先禁用外键检查,然后在删除完表之后再启用外键检查。具体的解决方法如下所示:

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

然而,如果我们在创建一个迁移文件时需要添加和删除特定的列,上述方法就不适用了。例如,如果我们想要给users表添加一个列,但使用上述命令会删除整个users表,这可能是灾难性的。在这种情况下,更好的做法是在down方法中使用回滚操作。

0