Laravel删除迁移中的外键

时间:2018-08-15 14:31:24

标签: php mysql laravel laravel-5.6

我想创建一个将删除表的迁移。我这样创建了迁移:

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:
     

更改表devices删除外键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 个答案:

答案 0 :(得分:4)

您可以使用此答案。 https://stackoverflow.com/a/30177480/8513937

将列名作为数组传递给 dropForeign 。在内部,Laravel删除关联的外键。

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

答案 1 :(得分:3)

只需删除整个表格(documentation):

Schema::drop('devices');

答案 2 :(得分:1)

您只需要在删除表之前禁用外键检查,然后按如下所示再次启用它们:

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

答案 3 :(得分:0)

尝试这种方式...

  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');
    });
  }