6
4

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 5 years have passed since last update.

N対Nのモデルを表現する方法

Posted at

N対Nのモデルとは

複数のモデルAと複数のモデルBが紐づいているデータ設計です。つまり複数対複数。

例えば、ユーザーとプロジェクトの関係にしてみましょう。

ユーザー側から見た場合

  • ユーザーAはプロジェクト1とプロジェクト2に紐付く
  • ユーザーBはプロジェクト1とプロジェクト2に紐付く
  • ユーザーCはプロジェクト2とプロジェクト3に紐付く

といった感じです。

プロジェクト側から見た場合

  • プロジェクト1はユーザーAとユーザーBに紐付く
  • プロジェクト2はユーザーAとユーザーBとユーザーCに紐付く
  • プロジェクト3はユーザーCに紐付く

といった感じです。

参考図

スクリーンショット 2019-03-29 13.39.15.png

データベースでどう表現するか

1対1や1対Nの場合

1対1や1対Nの場合は、片方のテーブルに外部キーを入れます。

1人のユーザーは1つのグループにしか属せないN対1の関係は下記のような感じです。

Groupテーブル

id name
1 group1
2 group2
3 group3

Userテーブル

id name group_id(外部キー)
1 user1 2
2 user2 2
3 user3 3
4 user4 1

N対Nの場合

中間テーブルを作り、中間テーブル側に両者のモデルの外部キーを入れます。

1人のユーザーは複数のプロジェクトに所属できる。また、1つのプロジェクトには複数のユーザーが所属する場合。

Projectテーブル

id name
1 project1
2 project2
3 project3

Userテーブル

id name
1 userA
2 userB
3 userC

UserProjectテーブル

user_id(外部キー) project_id(外部キー)
1 1
1 2
2 1
2 2
3 2
3 3

参考図

スクリーンショット 2019-03-29 13.39.15.png

6
4
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
6
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?