LoginSignup
0
0

More than 5 years have passed since last update.

[Laravel5.1]マイグレーションでindexを作成・削除しようとするとエラーになる

Last updated at Posted at 2017-08-22

はじめに

image.png

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

所感

こんな感じ?

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0