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

はじめに

外部キー制約とは、2つのテーブルを 親テーブル子テーブル にして生合成を保つために用いられる。

webアプリに次のテーブルがあるとする。(イメージはツイッターなどのアプリ)

  • 親テーブル:usersテーブル
  • 子テーブル:postsテーブル

ここで注意するのは、誰が投稿したかがわかるuser_idというカラムがpostsテーブルにあること

ルール

migrationsフォルダに親よりも先に子を作るとうまくいかなくなるらしいので注意が必要

まずは//1のようにuser_idを作成します。

子テーブル

databases/migration/create_posts_table.php
public function up()
{
    Schema::create('posts', function (Blueprint $table) {
        $table->id();
        $table->string('name')->unique();
        $table->unsignedBigInteger('user_id'); //1 外部キー ※型には注意!
        $table->foreign('user_id')->references('id')->on('users');//2 外部キー制約をつける 
        $table->timestamps();
    });
}

この時注意しなければならないのは、user_idデータ型は何でもいいわけではない!
usersテーブルのidカラムと同じでなければならない!

デフォルトのusersテーブルではidカラムのデータ型はunsignedBigInteger型なので、作成するuser_idのデータ型もunsignedBigInteger型でなければなりません。

親テーブル

databases/migration/create_users_table.php
public function up()
{
    Schema::create('users', function (Blueprint $table) {
        $table->id(); // ここが unsignedBigInteger型
        $table->string('name')->unique();
        $table->timestamps();
    });
}

次に//2で外部キー制約をかける

次に、//2のように外部キー制約を実装する。

子テーブル

databases/migration/create_posts_table.php
$table->foreign('user_id')->references('id')->on('users');//2 外部キー制約をつける

1. ->foreign('xxx')で外部キー制約したいカラムを指定する
2. ->references('yyy')で参照したいカラム名を指定する
3. ->on('zzz')でその参照したいカラムがあるテーブル名を指定する

これで、userテーブルにあるidカラムpostsテーブルのuser_idに参照させ、外部キー制約することができる!

実はもう一つ方法がある(省略型)

foreignIdメソッドを使うことで前に書いた方法よりも短く書くことができる。

子テーブル

public function up()
{
    Schema::create('posts', function (Blueprint $table) {
        $table->id();
        $table->string('name')->unique();
        $table->unsignedBigInteger('user_id'); //1 外部キー ※型には注意!
-        $table->foreign('user_id')->references('id')->on('users');//2 外部キー制約をつける 
+        $tabel->foreignId('user_id')->constrained();//2 ここで foreignIdメソッドを使う
        $table->timestamps();
    });
}
$tabel->foreignId('user_id')->constrained();

1. 外部キー制約したいカラム名をforeignIdメソッドの引数に与える。
2. constrainedメソッドはforeignIdメソッドに与えられた引数からどのテーブルのどのカラムを参照したいのかを判断してくれる。

よってuesr_idをforeignidメソッドに与えると,constrainedメソッドがuser_id = usersテーブルのidカラムを参照したいと判断してくれる。

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?