如何检查索引是否存在于 Laravel 迁移中?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/45882990/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can indexes be checked if they exist in a Laravel migration?
提问by Oladipo
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');
}
})
Something that looks like the above. (apparently, hasIndex() doesn't exist)
看起来像上面的东西。(显然,hasIndex() 不存在)
回答by admirko
Using "doctrine-dbal" that Laravel uses is better solution:
使用 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");
})
回答by chiliNUT
The mysql query
mysql 查询
SHOW INDEXES FROM persons
SHOW INDEXES FROM persons
will give you back all of the indexes on the table, however it includes additional info other than just the names. In my setup, the column containing the name is called Key_name
so lets get a collection of key names
将为您返回表上的所有索引,但它包括除名称之外的其他信息。在我的设置中,包含名称的列被称为Key_name
所以让我们获取键名称的集合
collect(DB::select("SHOW INDEXES FROM persons"))->pluck('Key_name')
And since its a collection you can use contains
so finally we have:
因为它是一个你可以使用的集合,contains
所以最后我们有:
if (collect(DB::select("SHOW INDEXES FROM persons"))->pluck('Key_name')->contains('persons_body_unique')) {
$table->dropUnique('persons_body_unique');
}
回答by dipenparmar12
In the simple form, you can do this
以简单的形式,您可以执行此操作
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");
}
})