LoginSignup
66
41

More than 5 years have passed since last update.

Laravel 5.8 にて["SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint"]エラー

Posted at

Laravel 5.8 にて Cannot add foreign key constraint が出たときの対応

さきに答え書くと、

型がbigIncrementsorbigIntegerで一致してるか確認してみて〜

Laravel 5.8だとphp artisan make:migration 〜で生成したテーブル定義では、
テーブルのメインidの型はbigIncrementsになってる。

経緯

わーいLaravel 5.8 つかってみよ〜としたら、php artisan migrateで早速つまづいた。
以下のようなテーブル定義でmigrate実行したらエラー。


//質問テーブル
    public function up()
    {
        Schema::create('questions', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('title');
            $table->string('slug');
            $table->string('body');

            $table->integer('category_id')->unsigned();
            $table->integer('user_id')->unsigned();
            $table->timestamps();
        });
    }

//返答テーブル
    public function up()
    {
        Schema::create('replies', function (Blueprint $table) {
            $table->bigIncrements('id');

            $table->text('body');
            $table->integer('question_id')->unsigned();
            //外部キー制約
            $table->foreign('question_id')->references('id')
                ->on('questions')->onDelete('cascade');
            $table->integer('user_id');
            $table->timestamps();
        });

//エラー
   Illuminate\Database\QueryException  : SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL: alter table `replies` add constraint `replies_question_id_foreign` foreign key (`question_id`) references `questions` (`id`) on delete cascade)

  at /var/www/bitfumes/vendor/laravel/framework/src/Illuminate/Database/Connection.php:664
    660|         // If an exception occurs when attempting to run a query, we'll format the error
    661|         // message to include the bindings with SQL, which will make this exception a
    662|         // lot more helpful to the developer instead of just the database's errors.
    663|         catch (Exception $e) {
  > 664|             throw new QueryException(
    665|                 $query, $this->prepareBindings($bindings), $e
    666|             );
    667|         }
    668| 

  Exception trace:

  1   PDOException::("SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint")
      /var/www/bitfumes/vendor/laravel/framework/src/Illuminate/Database/Connection.php:458

  2   PDOStatement::execute()
      /var/www/bitfumes/vendor/laravel/framework/src/Illuminate/Database/Connection.php:458

  Please use the argument -v to see more details.

対応

んじゃぐぐってみっか。
SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint でぐぐると、先人たちが

  • テーブルの生成順序がおかしいのでは?外部キーを参照するテーブルが存在してないのでは?
  • 制約キーのっけるカラムと、制約キーとして参照するカラムの型が一致してないのでは?

といった事例あり。たしかに確認してみると、自分の場合は

//questions 
$table->bigIncrements('id');
//replies
$table->integer('question_id')->unsigned();
            //外部キー制約
            $table->foreign('question_id')->references('id')
                ->on('questions')->onDelete('cascade');

で型ずれてる。。。
ということで、以下なおしたらエラー解消されました◎

//replies
$table->bigInteger('question_id')->unsigned();
        ^^^^^^^^^^^
            //外部キー制約
            $table->foreign('question_id')->references('id')
                ->on('questions')->onDelete('cascade');

ちなみに、参照する側のテーブルのidをincrementsにしてもOKのようです。
以下参考URLのBe Careful: Laravel 5.8 Added bigIncrements As Defaults
には英語ですが、そのように記述が。
公式が変更点としてbigIncrementsorbigIntegerを取り上げてなかったことに、この記事の方おかんむりでした。

参考URL
Be Careful: Laravel 5.8 Added bigIncrements As Defaults
【メモ】Laravelで外部キー制約付きのテーブルをマイグレーションする時に気をつけた方がよかった点
laravel5.7 外部キーエラー SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint

Added bigIncrements

66
41
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
66
41