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

Php 如果索引存在于Laravel迁移中,如何检查它们?,php,mysql,laravel,database-migration,Php,Mysql,Laravel,Database Migration,准备迁移时,尝试检查表上是否存在唯一索引,如何实现 Schema::table('persons', function (Blueprint $table) { if ($table->hasIndex('persons_body_unique')) { $table->dropUnique('persons_body_unique'); } }) 看起来像上面的东西。(显然,hasIndex()不存在)mysql查询 显示人员索引 将返回表上的所有

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

Schema::table('persons', function (Blueprint $table) {
    if ($table->hasIndex('persons_body_unique')) {
        $table->dropUnique('persons_body_unique');
    }
})
看起来像上面的东西。(显然,hasIndex()不存在)

mysql查询

显示人员索引

将返回表上的所有索引,但它包含除名称以外的其他信息。在我的设置中,包含名称的列被称为
Key\u name
,因此让我们获得一组密钥名称

collect(DB::select("SHOW INDEXES FROM persons"))->pluck('Key_name')
由于它是一个集合,您可以使用
包含
,因此最后我们有:

if (collect(DB::select("SHOW INDEXES FROM persons"))->pluck('Key_name')->contains('persons_body_unique')) {
        $table->dropUnique('persons_body_unique');
}
使用Laravel使用的“原则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");
});

以简单的形式,您可以这样做

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

这不应该是公认的答案,因为它不是跨dbms的(“可移植的”,不是特定于供应商的)。@admirko的答案要好得多,因为它超越了Laravel的基础理论层,而不是“本机查询”。如上所述,这应该是正确的答案,因为它超越了Laravel的理论,不使用本机查询。我可以在5.2中确认这一点,在我从repo安装doctrine dbal包之后。请注意,
listTableIndexes()
将以小写形式返回索引的名称。如果要在将来进行其他迁移,请使用$table对象来获取名称<代码>$IndexFound=$sm->listTableIndexes($table->getTable())