はじめに
Laravelのマイグレーションから、カラムにインデックスをセットしたり削除したりしようとしたときにハマったので。
[PDOException]
SQLSTATE[42000]: Syntax error or access violation: 1091 Can't DROP '(index_column)'; check that column/key exists
こんな感じのエラーが出ます。
hasColumn
とかhasTable
とかはあるのに、hasIndex
がないのはどうしてなのか。
というわけで作ります。
コード
(migrationfile).php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class MigrationFile extends Migration
{
public $tableName = 'sample_table';
public $connect = 'mysql_test';
public function up() {
Schema::connection($this->connect)->table($this->tableName, function(Blueprint $table) {
$indexes = \DB::connection($this->connect)->select(\DB::raw("SHOW INDEX FROM {$this->tableName};"));
// インデックス削除
$key = 'index_1';
if ($this->hasIndex($indexes, $key))
{
$table->dropIndex([$key]);
}
// インデックス作成
$key = 'index_2';
if (!$this->hasIndex($indexes, $key))
{
$table->index($key);
}
});
}
public function down() {
}
/**
* hasIndex
* @parameter : indexes as object, $key as string
* @return : true or false
**/
private function hasIndex($indexes, $key) {
foreach ($indexes as $index) {
if ($index->Column_name == $key)
{
return true;
}
}
return false;
}
所感
こんな感じ?