3
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.

【エラー備忘録】外部キー制約のエラー General error: 1215 Cannot add foreign key constraint

Last updated at Posted at 2021-05-22

状況

php aritisan migrateを行うとターミナルでエラーが発生。

General error: 1215 Cannot add foreign key constraint

エラー内容

外部キー制約について、型の不一致が原因らしい。

原因となっているファイルはこれ。

2021_05_01_103119_create_room_players_table
class CreateRoomPlayersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('room_players', function (Blueprint $table) {
            $table->engine = 'InnoDB';
            $table->bigIncrements('id');
            $table->interger("room_id")->comment('スコアボードのテーブル');
            //この行が問題

            //外部キー制約
            $table->foreign('room_id')
                    ->references('id')
                    ->on('rooms')
                    ->onDelete('cascade');
//以下省略


参照下のファイルはこれ。

2021_04_20_110007_create_rooms_table

class CreateRoomsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('rooms', function (Blueprint $table) {
            $table->bigIncrements('id')->unique
            ();
            $table->string("name")->comment('プレイ名')->unique();
            $table->string("password")->comment('スコアボードに入るためのパスワード');
            $table->timestamps();
        });
    }

外部キーの参照元のroomテーブルのidはbigIncrementsなので、bigIncrementsとintegerで一致していない。
またphpMyAdminで確認すると、roomテーブルのidは属性unsignedがついている。

外部キーを設定する場合、データ型が違うとだめらしい。

解決法

データ型を合わせるため、外部キーに指定するroom_idのintegerをbigIntegerに修正する。
(bigIncrementsとbigIntegerで合わせるため)

またroomテーブルのidの属性に合わせて、unsignedもつける。

2021_05_01_103119_create_room_players_table
class CreateRoomPlayersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('room_players', function (Blueprint $table) {
            $table->engine = 'InnoDB';
            $table->bigIncrements('id');
            $table->unsignedBigInteger("room_id")->comment('スコアボードのテーブル');

            //外部キー制約
            $table->foreign('room_id')
                    ->references('id')
                    ->on('rooms')
                    ->onDelete('cascade');
            $table->integer("user_id")

php artisan migrate:rollback
php artisan migrate:fresh を実行し、
php artisan migrate を実行すると、無事migrationできた。

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