使用定义的索引播种时引发错误

Error is raised on seeding with index defined

在 laravel 5.8 应用程序中,我创建了添加了 1 个字段和 1 个索引的迁移文件

class SubscriptionsTableAddIsFreeField extends Migration
{
    public function up()
    {
        Schema::table('subscriptions', function (Blueprint $table) {
            $table->boolean('is_free')->default(false)->after('source_service_subscription_id');
            $table->index([ 'user_id', 'is_free' ], 'subscriptions_user_id_is_free_index');

        });
    }

    public function down()
    {
        Schema::table('subscriptions', function (Blueprint $table) {
            $table->dropForeign('subscriptions_user_id_is_free_index');
            $table->dropColumn('is_free');
        });
    }

但是运行命令

php artisan migrate:refresh --seed

我收到错误:

: SQLSTATE[42000]: Syntax error or access violation: 1091 Can't DROP 'subscriptions_user_id_is_free_index'; check that column/key exists (SQL: alter table `vt2_subscriptions` drop foreign key `subscriptions_user_id_is_free_index`)

  at /mnt/_work_sdb8/wwwroot/lar/votes/vendor/laravel/framework/src/Illuminate/Database/Connection.php:664
    660|         // If an exception occurs when attempting to run a query, we'll format the error
    661|         // message to include the bindings with SQL, which will make this exception a
    662|         // lot more helpful to the developer instead of just the database's errors.
    663|         catch (Exception $e) {
  > 664|             throw new QueryException(
    665|                 $query, $this->prepareBindings($bindings), $e
    666|             );
    667|         }
    668| 

  Exception trace:

  1   Doctrine\DBAL\Driver\PDOException::("SQLSTATE[42000]: Syntax error or access violation: 1091 Can't DROP 'subscriptions_user_id_is_free_index'; check that column/key exists")
      /mnt/_work_sdb8/wwwroot/lar/votes/vendor/doctrine/dbal/lib/Doctrine/DBAL/Driver/PDOStatement.php:119

  2   PDOException::("SQLSTATE[42000]: Syntax error or access violation: 1091 Can't DROP 'subscriptions_user_id_is_free_index'; check that column/key exists")
      /mnt/_work_sdb8/wwwroot/lar/votes/vendor/doctrine/dbal/lib/Doctrine/DBAL/Driver/PDOStatement.php:117

  Please use the argument -v to see more details.

我的迁移定义有什么问题?

我知道 laravel 迁移有方法

if (Schema::hasTable('users')) {
    //
}

if (Schema::hasColumn('users', 'email')) {
    //
}

但是我可以检查索引吗?

有了这个 link 我找到了一个正确的检查:

Schema::table('subscriptions', function (Blueprint $table) {
    $sm = Schema::getConnection()->getDoctrineSchemaManager();
    $indexesFound = $sm->listTableIndexes('subscriptions');

    if(array_key_exists("subscriptions_user_id_is_free_index", $indexesFound)) {
        $table->dropUnique("subscriptions_user_id_is_free_index");
    }
    $table->dropColumn('is_free');
});

对我有用!