如何在Laravel迁移中检查索引是否存在?

如何在Laravel迁移中检查索引是否存在?

问题描述:

在准备迁移时尝试检查表上是否存在唯一索引,如何实现?

Trying to check if a unique index exists on a table when preparing a migration, how can it be achieved?

Schema::table('persons', function (Blueprint $table) {
    if ($table->hasIndex('persons_body_unique')) {
        $table->dropUnique('persons_body_unique');
    }
})

类似上面的内容. (显然,hasIndex()不存在)

Something that looks like the above. (apparently, hasIndex() doesn't exist)

使用Laravel使用的"doctrine-dbal"是更好的解决方案:

Using "doctrine-dbal" that Laravel uses is better solution:

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

    if(array_key_exists("persons_body_unique", $indexesFound))
        $table->dropUnique("persons_body_unique");
})