在Laravel迁移中删除外键

Krz*_*ski 6 migration laravel

我在从Laravel应用程序中删除一些外键时遇到问题.问题是当我尝试回滚迁移时:

php artisan migrate:rollback
Run Code Online (Sandbox Code Playgroud)

我不知道为什么我在控制台中有错误:

[Illuminate\Database\QueryException] SQLSTATE [42000]:语法错误或访问冲突:1091无法DROP'rope_user_user_id_foreign'; 检查列/密钥是否存在(SQL:alter table role_userdrop foreign key role_user_user_id_foreign)

[Doctrine\DBAL\Driver\PDOException] SQLSTATE [42000]:语法错误或访问冲突:1091无法DROP'rope_user_user_id_foreign'; 检查列/键是否存在

[PDOException] SQLSTATE [42000]:语法错误或访问冲突:1091无法DROP'rope_user_user_id_foreign'; 检查列/键是否存在

下面我展示了我的迁移类:

class UpdateRoleUserTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        schema::table('role_user',function(Blueprint $table){


            $table->foreign('user_id')->references('id')->on('users');
            $table->foreign('role_id')->references('id')->on('roles');

        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('role_user', function (Blueprint $table) {
        $table->dropForeign('role_user_user_id_foreign');
        $table->dropForeign('role_user_role_id_foreign');

    });
    }
}
Run Code Online (Sandbox Code Playgroud)

我的数据库表已由迁移类创建:

class CreateRoleUserTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('role_user', function (Blueprint $table) {

            $table->increments('id');
            $table->integer('user_id')->unsigned();
            $table->integer('role_id')->unsigned();

        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('role_user');
    }
}
Run Code Online (Sandbox Code Playgroud)

Kin*_*a T 10

在所有> 4.0版本的Laravel中,它允许将列名放入一个数组中,然后它将自行解析.我试图找到随附的文档,但他们似乎已将其遗漏.

在更新迁移中,请尝试以下操作:

Schema::table('role_user', function (Blueprint $table) {
  $table->dropForeign(['user_id']);
  $table->dropForeign(['role_id']);
});
Run Code Online (Sandbox Code Playgroud)

  • +1。很好的答案。你救了我。我不知道为什么在文档中这是错误的,即使在 Laravel 8 文档中也是如此。谢谢!! (2认同)

Gha*_*eak 8

我刚刚遇到了这个问题,问题是由于$table->dropForeign([column_name]);删除了索引而不是列本身。解决方案是在down函数中将索引放在一个块中,然后将实际列放在一个单独的块中。由于无法在与删除列的位置相同的连接中删除密钥,因此必须将它们放入单独的块中。

所以down函数应该是这样的:

public function down() {
    // drop the keys
    Schema::table('role_user', function (Blueprint $table) {
        $table->dropForeign(['user_id']);
        $table->dropForeign(['role_id']);
    });

   // drop the actual columns
   Schema::table('role_user', function (Blueprint $table) {
        $table->dropColumn('user_id');
        $table->dropColumn('role_id');

    });
}
Run Code Online (Sandbox Code Playgroud)

现在您可以运行php artisan migrate以运行该up函数并php artisan migrate:rollback运行该down命令并且该错误不再显示。

  • 这应该是正确的答案,因为它删除了列和外键。 (2认同)