0
0

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】SQLSTATE[42000]:1075 エラーの解消

Last updated at Posted at 2023-02-01

エラー内容

マイグレーションファイルを編集。

Schema::create('items', function (Blueprint $table) {
            $table->bigIncrements('id');               //自動で連番が割り振られる
            $table->unsignedBigInteger('user_id', 20); //ここが問題
            $table->string('name', 255);
            $table->string('description', 1000);
            $table->unsignedBigInteger('category_id'); //ここが問題
            $table->integer('price', 20);              //ここが問題
            $table->string('image', 100);
            $table->timestamps();
            
            $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
            $table->foreign('category_id')->references('id')->on('categories')->onDelete('cascade');
        });
php artisan migrate

マイグレーションを実行させたとき

SQLSTATE[42000]: Syntax error or access violation: 1075 Incorrect table definition; there can be only one auto column and it must be defined as a key (SQL: create table items (~)

というエラーが発生。
翻訳すると

sqlstate[42000]: 構文エラーまたはアクセス違反が発生しました。1075 テーブルの定義が正しくありません; auto 列は 1 つだけで、キーとして定義する必要があります (SQL: create table items (~).

とのこと。

原因調査

integerは第二引数を指定してはいけないみたい。
Laravelの仕様だそう。

参考文献

解決方法

integer型の第二引数を削除

Schema::create('items', function (Blueprint $table) {
            $table->bigIncrements('id');               //自動で連番が割り振られる  
-           $table->unsignedBigInteger('user_id', 20);
+           $table->unsignedBigInteger('user_id');
            $table->string('name', 255);
            $table->string('description', 1000);
-           $table->unsignedBigInteger('category_id', 20);
+           $table->unsignedBigInteger('category_id');
-           $table->integer('price', 11);
+           $table->integer('price');
            $table->string('image', 100);
            $table->timestamps();
            
            $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
            $table->foreign('category_id')->references('id')->on('categories')->onDelete('cascade');
        });
php artisan migrate

マイグレーションを実行させたとき

成功。

まとめ

integer型は第二引数を設定しない

その他

unsignedBigInteger型のデフォルト値は「20」
integer型のデフォルト値は「11」
データ型

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?