在定义索引的种子上引发错误

在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')) {
    //
}

但是我可以检查索引吗?

zhanghua02302 回答:在定义索引的种子上引发错误

通过此How can indexes be checked if they exist in a Laravel migration?链接,我发现了适当的检查:

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

对我有用!

本文链接:https://www.f2er.com/3145185.html

大家都在问