0
3

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勉強してたら外部キーとかいう知らない言葉に出くわしたので、その正体に迫ったという話。

あらすじ

Laravelでwebアプリを制作中、usersテーブルとnewsテーブルという2つのテーブルを紐付けようとした。
具体的にはnewsテーブルにuser_idというカラムを追加し、そこにusersテーブルのidの値を格納しようとした。
参考にしてる教材がいきなり外部キーとかいう謎ワードぶっこんできた挙句解説しないという暴挙に出たため自力で探りに行った。

具体的な話

user_idを追加するためのmigrationファイルを作成

migrationファイル
public function up()
{
    Schema::table('news', function (Blueprint $table) {
        $table->integer('user_id')->unsigned();

        // ここが意味わからんかった
        $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade);
    });
}

結論

複数のテーブルを連動させる場合、テーブル同士の整合性を保つための仕組みらしい。

例えばユーザーAが複数のニュースを作成し、その後ユーザーAを削除した場合に、作成したニュースも同時に削除されるようにする、など。

コードを詳しく見ると、foreign('user_id')でuser_idを外部キーに指定し、references('id')で主テーブル(usersテーブル)のidを指定し、on('users')で主テーブルを指定している。
onDelete()はuserが削除・更新された場合の処理を指定している。
引数にcascadeを取ると親レコードが削除されれば子レコードも削除される。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?