1
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 5 years have passed since last update.

Laravel7マイグレートエラー(SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint)

1
Posted at

Laravelで、タグ付けのできる投稿サイトをチームで制作しています。
投稿テーブル(reviews)を先に作っていたのですが、今回タグテーブル(tags)を作成し、reviewsとはreview_tagという中間テーブルで多対多のリレーションを作成したいです。
しかし、マイグレートした時にエラーで少しだけ苦しんだのでメモしておきます。

問題点はここ

$ php artisan migrate

Migrating: 2020_09_19_035606_create_tags_table
Migrated:  2020_09_19_035606_create_tags_table (0.08 seconds)
Migrating: 2020_09_19_053140_create_review_tag_table

   Illuminate\Database\QueryException 

  SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL: alter table `review_tag` add constraint `review_tag_tag_id_foreign` foreign key (`tag_id`) references `tags` (`id`) on delete cascade)

外部キーが設定できないぜと仰っているようです。いろいろ調べると、主キーidの設定でBIGINTとINTは両立できない模様。

エラーになった時の3つの各テーブルのマイグレーションファイルは下のようになっていました。主キーを設定している箇所にご注目ください。

reviewsテーブルのマイグレーションファイル↓

XXXXXX_create_reviews_table.php
class CreateReviewsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('reviews', function (Blueprint $table) {
            $table->id();//BIGINTの主キー
            $table->date('live_date');
            $table->string('title', 255);
            $table->text('text');
            $table->timestamps(0);
            $table->foreignId('user_id')->constrained('users');
        });
    }

tagsテーブルのマイグレーションファイル↓

XXXXXX_create_tag_table.php
class CreateTagsTable extends Migration
{
     * @return void
     */
    public function up()
    {
        Schema::create('tags', function (Blueprint $table) {
            $table->increments('id');//BIGINTではないid主キー
            $table->string('tag_name', 30);
            $table->string('info');
            $table->string('url');
            $table->timestamps();
        });
    }

review_tag中間テーブルのマイグレーションファイル↓

XXXXXX_create_review_tag_table.php
public function up()
    {
        Schema::create('review_tag', function (Blueprint $table) {
            $table->increments('id');//BIGINTではないid主キー
            $table->timestamps();
            $table->foreignId('review_id')->constrained('reviews')->onDelete('cascade'); //foreignIdはunsignedBigIntegerのエイリアス
            $table->foreignId('tag_id')->constrained('tags')->onDelete('cascade'); //foreignIdはunsignedBigIntegerのエイリアス
        });
    }

こう解決しました

まず、MySQLにてdrop table テーブル名;でtagsとreview_tagを一旦削除。
次に、tagsとreview_tagのマイグレーションファイルにて、$table->increments('id');を$table->id();に変更。
(正直、reviewsと中間テーブルを挟んで間接的にしか繋がってない(?)tagsテーブルの方のマイグレーションファイルのidも修正が必要だったのかは不明...)
こうして再度マイグレートしたら、エラー出ずに上手くいきました。

$ php artisan migrate
Migrating: 2020_09_19_035606_create_tags_table
Migrated:  2020_09_19_035606_create_tags_table (0.03 seconds)
Migrating: 2020_09_19_053140_create_review_tag_table
Migrated:  2020_09_19_053140_create_review_tag_table (0.09 seconds)

以上になります。ごもし指摘などあれば、ぜひよろしくお願いします。

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