LoginSignup
0
0

More than 3 years have passed since last update.

laravel version5.7以前でマイグレーションエラーが発生した際に行ったこと

Posted at

laravel 5.7を使用したアプリ開発時に「php artisan migrate」を行ったところ次のようなエラーメッセージが出た。

SQLSTATE[HY000]: General error: 3780 Referencing column 'user_id' and referenced column 'id' in foreign key constraint 'posts_user_id_foreign' are incompatible.

user_idがどうこう言っていたのでmigrationファイルを確認したが異常は見つからず…。

その時の自分が書いたコードが以下の通り

create_users_table.php

public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('name');
            省略
        });
    }
create_posts_table.php

public function up()
    {
        Schema::create('posts', function (Blueprint $table) {
            中略
            $table->integer('user_id')->unsigned();
            $table->foreign('user_id')
                  ->references('id')->on('users')
                  ->onDelete('cascade');
        });
    }

しばらくGoogleで検索しているとこのような下記のような記事が見つかった

Laravel 外部キー制約エラー General error: 3780 Referencing column

記事によるとどうやら外部キー制約によるエラーであることが判明。

記事の通り確認すると問題の箇所は
「create_posts_table」のほうではなく「create_users_table」の方にあった。

$table->bigIncrements('id');

と書かれていたのを

$table->Increments('id');

へと修正し、再度migrateを実行したところうまく行った!解決!!

どうやら自分が参照していたのはlaravel5.8以降のバージョンの記事であったらしくそれより以前のバージョンを使用していたためうまくかなかったらしいとのこと。

laravelにはバージョン別に様々な記事や参考書などがあるが自身が使っているバージョンの把握も大切だと学んだ。

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