laravel6.0 Schema缺少hasIndex方法的替代方案

转自https://stackoverflow.com/questions/45882990/how-can-indexes-be-checked-if-they-exist-in-a-laravel-migration

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

Schema::table('persons', function (Blueprint $table) {
    if ($table->hasIndex('persons_body_unique')) {
        $table->dropUnique('persons_body_unique');
    }
})

最佳实践:

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

或者这样,在无唯一索引时不会执行迁移文件:

$sm = Schema::getConnection()->getDoctrineSchemaManager();
$indexsFound = $sm->listTableIndexes('ext');
        
if (array_key_exists('ext_person_unique', $indexsFound)) {
  Schema::table('ext', function (Blueprint $table) {
     $table->dropUnique('ext_person_unique');
      $table->index('person');
   });
}

 

posted @ 2022-07-15 16:12  千逸山水  阅读(59)  评论(0)    收藏  举报