Laravel drop foreign Key in Migration

。_饼干妹妹 提交于 2020-01-24 03:45:13

问题


I want to create a Migration which shall drop a table. I created the Migration like this:

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

And now I try to drop it like this:

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

But I get following error:

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

回答1:


You just need to disable foreign key checks before you drop the table then enable them again after like this:

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



回答2:


You can use this answer. https://stackoverflow.com/a/30177480/8513937

Pass to dropForeign the column name as array. Internally, Laravel drops the associated foreign key.

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



回答3:


Just drop the whole table (documentation):

Schema::drop('devices');



回答4:


Try this ways...

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


来源:https://stackoverflow.com/questions/51860723/laravel-drop-foreign-key-in-migration

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!