[英]How can indexes be checked if they exist in a Laravel migration?
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() 不存在)
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");
});
The mysql query mysql 查询
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');
}
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");
}
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.