0
1

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.

中間テーブルがあるDB設計

Last updated at Posted at 2020-04-11

はじめに

次はもっと複雑です。
中間テーブルを用いたDB設計をしていきます。
紙に書いた後にQiitaに書き起こす。
効率よくならんものか、この頭…💦

…と、言ってないでさっさとやりましょう。

usersテーブル

Column Type Options
email string null: false
password string null: false
username string null: false
※email/password/username空欄を許可しない「NOT NULL」を設定。【null: false】

Association

  • has_many :posts
  • has_many :comments
※usersテーブル⇆postsテーブル = 「1対多」
※usersテーブル⇆commentsテーブル = 「1対多」
なので両方とも【has_many】

postsテーブル

Column Type Options
title text null: false
text text null: false
user_id integer null: false, foreign_key: true
※/title/text/user_idは空欄を許可しない「NOT NULL」を設定。【null: false】
※user_idを外部キーとして設定。【foreign_key: true】

Association

  • belongs_to :user
  • has_many :comments
  • has_many :posts_tags
  • has_many :tags, through: :posts_tags
※postsテーブル⇆usersテーブル = 「多対1」なので【belongs_to】
※postsテーブル⇆commentsテーブル = 「1対多」
※postsテーブル⇆posts_tagsテーブル = 「1対多」

 →【has_many】

※postsテーブル⇆tagsテーブル = 「1対多」かつ、中間テーブルとしてposts_tagsテーブルを設けている。

 →【has_many **,through:】

tagsテーブル

Column Type Options
text text null: false

Association

  • has_many :posts_tags

  • has_many :posts, through: :posts_tags

※tagsテーブル⇆posts_tagsテーブル = 「1対多」なので【has_many】
※tagsテーブル⇆postsテーブル = 「1対多」かつ、中間テーブルとしてposts_tagsテーブルを設けている。

 →【has_many **, through:】

posts_tagsテーブル

Column Type Options
post_id integer null: false, foreign_key: true
tags_id integer null: false, foreign_key: true

Association

  • belongs_to :post
  • belongs_to :tag

commentsテーブル

Column Type Options
text text null: false
user_id integer null: false, foreign_key: true
group_id integer null: false, foreign_key: true

Association

  • belongs_to :post
  • belongs_to :user

まとめ

 ・エンティティとその属性を明確に
 ・エンティティ間のリレーションを明確に
 ・どのデータにどんな制約がつくか
 ・ER図にして表す

 これらが大事だと思った。

以上

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?