【问题标题】:Laravel drop foreign Key in MigrationLaravel 在迁移中删除外键
【发布时间】:2019-01-22 10:48: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

【问题讨论】:

    标签: php mysql laravel laravel-5.6


    【解决方案1】:

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

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

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

    【讨论】:

    • 当你没有给它一个 Laravel 默认设置的不同的 FK 名称时,这可以工作。
    【解决方案2】:

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

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

    【讨论】:

      【解决方案3】:

      试试这个方法...

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

      【讨论】:

      • 有一个外键我放不下它
      【解决方案4】:

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

      Schema::drop('devices');
      

      【讨论】:

      • 嗨,有一个外键 Client_id,所以我不能轻易放弃它
      • Integrity constraint violation: 1217 Cannot delete or update a parent row: a foreign key constraint fails (SQL: drop table devices)
      • 其他表中是否存在引用devices表的外键?
      • 当我们不在 up 方法中创建表时,为什么要在 down 方法中删除整个表?
      • 当它有一个外键时,你不能删除整个表。
      猜你喜欢
      • 2018-11-10
      • 2015-03-25
      • 2016-11-13
      • 2020-06-05
      • 2016-12-16
      • 2021-01-03
      • 2016-06-06
      • 2019-09-23
      • 2019-01-29
      相关资源
      最近更新 更多