Laravel放弃了外国移民的关键

Jon*_* xx 6 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');
});
Run Code Online (Sandbox Code Playgroud)

现在我试着像这样放弃它:

    Schema::table('devices', function (Blueprint $table) {
        $table->dropForeign('devices_client_id_foreign');
        $table->drop('devices');
    });
Run Code Online (Sandbox Code Playgroud)

但我得到以下错误:

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:
Run Code Online (Sandbox Code Playgroud)

alter table devicesdrop 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
Run Code Online (Sandbox Code Playgroud)

小智 22

你可以使用这个答案。/sf/answers/2112423631/

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

$table->dropForeign(['client_id']);
Run Code Online (Sandbox Code Playgroud)


小智 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');
    });
  }
Run Code Online (Sandbox Code Playgroud)


小智 6

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

DB::statement('SET FOREIGN_KEY_CHECKS=0;');
Schema::dropIfExists('devices');
DB::statement('SET FOREIGN_KEY_CHECKS=1;');
Run Code Online (Sandbox Code Playgroud)