如何在准备迁移时检查表中是否存在唯一索引?
Schema::table('persons', function (Blueprint $table) {
if ($table->hasIndex('persons_body_unique')) {
$table->dropUnique('persons_body_unique');
}
})
类似上述内容的东西。(显然,hasIndex()方法不存在)
如何在准备迁移时检查表中是否存在唯一索引?
Schema::table('persons', function (Blueprint $table) {
if ($table->hasIndex('persons_body_unique')) {
$table->dropUnique('persons_body_unique');
}
})
类似上述内容的东西。(显然,hasIndex()方法不存在)
使用 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");
});
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');
}
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");
}
})
listTableIndexes()
方法返回的索引名称是 小写字母。 - RyanNerd$indexesFound = $sm->listTableIndexes($table->getTable());
- JKOlaf