如果索引存在于Laravel迁移中,如何检查索引?

时间:2017-08-25 13:54:15

标签: php mysql laravel database-migration

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

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

看起来像上面的东西。 (显然,hasIndex()不存在)

3 个答案:

答案 0 :(得分:22)

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

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

答案 1 :(得分:5)

mysql查询

SHOW INDEXES FROM persons

将返回表中的所有索引,但它包含除名称之外的其他信息。在我的设置中,包含名称的列称为Key_name,因此我们可以获得一组键名

collect(DB::select("SHOW INDEXES FROM persons"))->pluck('Key_name')

由于它是一个集合,你可以使用contains,所以最后我们有:

if (collect(DB::select("SHOW INDEXES FROM persons"))->pluck('Key_name')->contains('persons_body_unique')) {
        $table->dropUnique('persons_body_unique');
}

答案 2 :(得分:0)

以简单的形式,您可以执行此操作

Schema::table('persons', function (Blueprint $table) {
    $index_exists = collect(DB::select("SHOW INDEXES FROM persons"))->pluck('Key_name')->contains('persons_body_unique');
    if ($index_exists) {
        $table->dropUnique("persons_body_unique");
    }
})