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?

【Laravel】マイグレーション 任意のカラムを外部キー指定

Posted at

例えば、usersテーブルがあり、そのテーブルを参照するpostsテーブルがあるとします。
Laravelでは、usersテーブルとpostsを紐づける外部キーはuser_idと命名するのが一般的でしょう。

usersテーブルのid(主キー)とpostsのuser_idを紐づけを行いたい場合のマイグレーション。

sample.php
Schema::table('users', function (Blueprint $table) {
    $table->id();
    $table->string('name');
});

Schema::table('posts', function (Blueprint $table) {
    $table->id();
    $table->foreignId('user_id')
        ->constrained()
        ->onUpdate('cascade')
        ->onDelete('cascade');
});

しかし、例えばusersテーブルに会員番号(user_number)というカラムがあったとして
user_numberで外部キー結合を行いたい場合のマイグレーションは以下のようになります。

sample.php
Schema::table('users', function (Blueprint $table) {
    $table->id();
    $table->string('name');
    $table->unsignedInteger('user_number')->unique();
});

Schema::table('posts', function (Blueprint $table) {
    $table->id();
    $table->unsignedInteger('user_number');
    $table->foreign('user_number')
        ->references('user_number')
        ->on('users')
        ->onUpdate('cascade')
        ->onDelete('cascade');
});

注意点

user_numberの型はusersとpostsで両方とも同じ型にして下さい。
また、予期しないバグを防ぐためusersのuser_numberはユニークにすることをおすすめします。

usersとpostsを結合する場合

sample.php
$posts = Post::join('users', 'posts.user_number', '=', 'users.user_number')
    ->get();
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?