Ola*_*ola 9 php mysql database-migration laravel
在准备迁移时,尝试检查表上是否存在唯一索引,如何实现?
Schema::table('persons', function (Blueprint $table) {
if ($table->hasIndex('persons_body_unique')) {
$table->dropUnique('persons_body_unique');
}
})
Run Code Online (Sandbox Code Playgroud)
看起来像上面的东西.(显然,hasIndex()不存在)
小智 27
使用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");
})
Run Code Online (Sandbox Code Playgroud)
mysql查询
SHOW INDEXES FROM persons
将返回表上的所有索引,但是它不仅包含名称,还包含其他信息。在我的设置中,包含名称的列被调用,Key_name因此让我们获取键名称的集合
collect(DB::select("SHOW INDEXES FROM persons"))->pluck('Key_name')
Run Code Online (Sandbox Code Playgroud)
由于它是一个集合,您可以使用,contains所以最终我们有了:
if (collect(DB::select("SHOW INDEXES FROM persons"))->pluck('Key_name')->contains('persons_body_unique')) {
$table->dropUnique('persons_body_unique');
}
Run Code Online (Sandbox Code Playgroud)
在简单的形式中,您可以这样做
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");
}
})
Run Code Online (Sandbox Code Playgroud)