LoginSignup
0
0

More than 1 year has passed since last update.

【Laravel】SQLSTATE[HY000]: 1005 エラーの解消

Last updated at Posted at 2023-02-01

エラー内容

マイグレーションファイルを用意

  • 2023_02_01_153621_create_items_table.php
  • 2023_02_01_153622_create_categories_table.php
    マイグレーションファイル.PNG

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

ポイント
「items」の「category_id」を「categories」の「id」に対して外部キーの設定をしている

Schema::create('items', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->unsignedBigInteger('user_id');
            $table->string('name', 255);
            $table->string('description', 1000);
            $table->unsignedBigInteger('category_id');
            $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

エラー出力

SQLSTATE[HY000]: General error: 1005 Can't create table プロジェクト名.items(errno: 150 "Foreign key constraint is incorrectly formed") (SQL: alter table items add constraint items_category_id_foreign foreign key (category_id) references categories (id) on delete cascade)

翻訳すると

SQLSTATE[HY000]: 一般エラー: 1005 テーブル プロジェクト名.items を作成できません (errno: 150 "外部キー制約の形式が正しくありません") (SQL: テーブル items を変更すると、制約 items_category_id_foreign 外部キーが追加されます ( category_id) はカスケード削除で categories (id) を参照します)

とのこと。

原因

前提

php artisan migrate

マイグレーションは上から実行される。

現象

マイグレーションファイルを確認すると、

  • 2023_02_01_153621_create_items_table.php
  • 2023_02_01_153622_create_categories_table.php
    マイグレーションファイル.PNG

「items_table」が上
「categories_table」が下になっている。

先に「items_table」を生成しようとすると、
参照先のテーブル「categories_table」はないですよ。
というエラー。

解決方法

マイグレーションファイルの日付を変更(153621→153623)し
参照先のテーブル「categories_table」を先に生成させる

  • 2023_02_01_153622_create_categories_table.php
  • 2023_02_01_153623_create_items_table.php

マイグレーションファイル.PNG

マイグレーション実行

php artisan migrate

マイグレーションファイル.PNG

成功。

まとめ

マイグレーションを実行すると上のファイルから実行されていく。
変更するには日付を変更し、順番を変える。

その他

1005 エラーの原因は他にもあるみたい。

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