0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Laravelのphp artisan migrateで「Multiple primary key defined」エラー

Last updated at Posted at 2023-04-17

環境

  • Laravel 10.4.1
  • データベース MariaDB 5.5.68
  • PHP 8.2.4

状況

php artisan migrate で primary key を複数設定してはいけない、と怒られた。

SQLSTATE[42000]: Syntax error or access violation: 1068 Multiple primary key defined (Connection: mysql, SQL: alter table test add primary key (id))

実行しようとしたmigrationファイル

PHP:\database\migrations\2023_**_**_135543_create_todo_table.php
Schema::create('test', function (Blueprint $table) {
    $table->integer('id')->primary()->autoIncrement();
    $table->integer('user_id');
    $table->string('title', 100);
    $table->text('todo');
    $table->dateTime('add_date');
    $table->timestamp('update_date')->useCurrent()->useCurrentOnUpdate();
    $table->charset = 'utf8mb4';
    $table->collation = 'utf8mb4_general_ci';
});

調べると、どうもこの行が問題で↓
$table->integer('id')->primary()->autoIncrement();
auto_incrementを有効にすると自動でprimary keyがついてきてしまうので、2重になってしまうらしい。
なんだか強制的にこうされてしまうと、問題が起こることもあるのでは?という気がするのだけれど、、、汗
参考:primary key のカラムとは別に auto_incremen するカラムがあるテーブルを migrate したい

確認のため、--pretend で実行されるSQLを確認してみる(実行はされない)。
参考:Laravel Migration コマンドまとめ

php artisan migrate --pretend

生成されたSQL

 create table `test` (
`id` int not null auto_increment primary key, 
`user_id` int not null, 
`title` varchar(100) not null, 
`todo` text not null, 
`add_date` datetime not null, 
`update_date` timestamp not null default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP) 
default character set utf8mb4 
collate 'utf8mb4_general_ci'
   alter table `todo` add primary key (`id`)

確かに、primary keyが2回出てくるので、

$table->integer('id')->primary()->autoIncrement();

$table->integer('id')->autoIncrement();
に修正し、
php artisan migrate --pretend
で確認すると、 primary keyが1つになった。
なので、再度 php artisan migrateしたら、成功。
なんだか->primary()と明示的に指定できないのが気持ち悪いけれど、仕方ない。

参考:同様のケース

primary key のカラムとは別に auto_incremen するカラムがあるテーブルを migrate したい

0
1
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
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?