LoginSignup
7
4

More than 3 years have passed since last update.

【Laravel】migrationで複合主キーのうち1つをincrementsに指定したい

Last updated at Posted at 2019-08-19

idをオートインクリメント
iduser_idtypeを複合主キーに設定したい。


class CreateFoosTable extends Migration
{
    public function up()
    {
        Schema::create('foos', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('user_id');
            $table->tinyInteger('type');
            $table->text('text');
            $table->timestamps();

            $table->primary(['id', 'user_id', 'type']);
        });
    }
}

マイグレーションを実行しようとするとエラーが出る

Syntax error or access violation: 1068 Multiple primary key defined

すでにプライマリーキーがすでに設定されているというエラー

$table->increments('id');で主キーを設定して
$table->primary(['id', 'user_id', 'type']);で再度複合主キーを設定しようとしている?

そう思ったので、idを一度integerに設定して主キーを設定した後にincrementsに変更してみた。


class CreateFoosTable extends Migration
{
    public function up()
    {
        Schema::create('foos', function (Blueprint $table) {
            $table->integer('id');
            $table->integer('user_id');
            $table->tinyInteger('type');
            $table->text('text');
            $table->timestamps();

            $table->primary(['id', 'user_id', 'type']);
        });

        Schema::table('foos', function (Blueprint $table) {
            $table->increments('id')->change();
        });
    }
}

requires Doctrine DBAL; install "doctrine/dbal".
doctrine/dbalを追加しろと言われたので追加

カラム変更
動作要件
カラムを変更する前に、composer.jsonファイルでdoctrine/dbalを確実に追加してください。Doctrine DBALライブラリーは現在のカラムの状態を決め、指定されたカラムに対する修正を行うSQLクエリを生成するために、使用しています。

$composer require doctrine/dbal

できた。

7
4
2

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
7
4