0
2

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

【Laravel】中間テーブルのmigrationファイルを作るときは順番に注意

Last updated at Posted at 2021-09-13

タイトルの通りですが、何も気にせずmigrationファイルをつらつら作っていたらエラー発生したので、忘れないようにメモです。

前提知識

Laravelのmigrationは作成日順に実行される。今日はとりあえずここさえ覚えてもらえればOKです。

2014_10_12_000000_create_users_table.php
2014_10_12_100000_create_password_resets_table.php
2019_08_19_000000_create_failed_jobs_table.php

こんな順番ですね。

さて本題

中間テーブルを作成する時にこのmigrationファイルの実行順番でエラーになりました。
が、よく考えてみれば当たり前の挙動でした。

テーブル構成(例)

rolesテーブル
role_usersテーブル(中間テーブル)
usersテーブル

migrationファイルを作る時に起こったこと

DB設計書通りの順番でrolesテーブル→role_usersテーブル→usersテーブルと php artisan make:migrationでファイルを作りました。
ファイルの先頭に付く日付は、
rolesテーブル
role_usersテーブル(中間テーブル)
usersテーブル
この順番になりますね。

その後php artisan migrateすると、、、

SQLSTATE[HY000]: General error: 1824 Failed to open the referenced table ....

中間テーブルで落ちました。外部キーの設定かな?と一瞬思いましたが、よく見ると参照できないって言っている。
あ、まだもう一個のテーブルが作られていない!

中間テーブルはこんな構成(例)

    public function up()
    {
        Schema::create('role_users', function (Blueprint $table) {
            $table->unsignedBigInteger('role_id');
            $table->unsignedBigInteger('user_id');
            $table->dateTimes();

            //外部キー制約
            $table->foreign('role_id')
                ->references('id')
                ->on('roles')
                ->onDelete('cascade');
            $table->foreign('user_id')
                ->references('id')
                ->on('users')
                ->onDelete('cascade');
            
            // 複合主キー
            $table->primary(['role_id', 'user_id']); 
        });
    }

中間テーブルが外部キーの設定をするため、usersテーブルを参照しにいくが、まだusersテーブルはmigrationが実行されていないため参照できなくてエラーになるというわけですね。

解決方法

解決方法は単純で、中間テーブルを最後に作ればいいだけです。

rolesテーブル
usersテーブル
role_usersテーブル(中間テーブル)

こんな感じですね。
これでエラーにならないはず。

補足

Laravel5.8系からはIDカラムがbigintになっているので、中間テーブル側も合わせて unsignedBigInteger にしないとダメです。

0
2
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
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?