0
0

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 2020-08-08

Migrationファイルを使って、リレーション設定を行う際のちょっとした注意メモ。

エラーがでたファイル
<?php
//-- 略
class CreatePostsTable extends Migration
{
    //-- 略
    public function up()
    {
        Schema::create('Posts', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('title');
            $table->bigInteger('user_id');
            $table->foreign('user_id')->references('id')->on('users');
            $table->timestamps();
        });
    }
}
//-- 略

上記のようなマイグレーションファイルをコマンドでmigrateしたときエラーが発生。
どうやら$table->foreign('user_id')->references('id')->on('users');のようにuser_idを外部キーとして使用している場合は、カラム定義の際に$table->bigInteger('user_id');という記述を$table->bigInteger('user_id')->unsigned();という感じでunsignedをつなげて書く必要があるようです。(MySQLの場合)

OKだったファイル
<?php
//-- 略
class CreatePostsTable extends Migration
{
    //-- 略
    public function up()
    {
        Schema::create('Posts', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('title');
            $table->bigInteger('user_id')->unsigned(); // 変更
            $table->foreign('user_id')->references('id')->on('users');
            $table->timestamps();
        });
    }
}
//-- 略

ちょっとしたメモでした。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?