laravel在迁移中删除外键

qyzbxkaa  于 2021-06-20  发布在  Mysql
关注(0)|答案(4)|浏览(384)

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

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
zfciruhq

zfciruhq1#

只需放下整张table(文档):

Schema::drop('devices');
xmq68pz9

xmq68pz92#

你可以用这个答案。https://stackoverflow.com/a/30177480/8513937
将列名作为数组传递给dropforeign。在内部,laravel丢弃相关的外键。

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

cczfrluj3#

试着这样。。。

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

z4bn682m4#

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

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

相关问题