How can indexes be checked if they exist in a Laravel migration?

一个人想着一个人 提交于 2020-01-01 08:35:23

问题


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)


回答1:


Using "doctrine-dbal" that Laravel uses is better solution:

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



回答2:


The mysql query

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

collect(DB::select("SHOW INDEXES FROM persons"))->pluck('Key_name')

And since its a collection you can use contains so finally we have:

if (collect(DB::select("SHOW INDEXES FROM persons"))->pluck('Key_name')->contains('persons_body_unique')) {
        $table->dropUnique('persons_body_unique');
}


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!