Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Defining multiple foreign keys in one table to many tables

I have 3 models:

Post:

  • id
  • title
  • body

Photo:

  • id
  • filepath

Comment:

  • id
  • post_id
  • body

and corresponding tables in DB. Now, if I want to have comments only for my posts I can simply add following foreign key: ALTER TABLE comment ADD FOREIGN KEY (post_id) REFERENCES post (id). But I want to have comments for other models (photo, profile, video, etc) and keep all comments in one table. How can I define foreign keys (i definitely need FKs for ORM) in such case?

like image 292
galymzhan Avatar asked Oct 29 '10 09:10

galymzhan


People also ask

Can we define multiple foreign keys in a table?

A table can have multiple foreign keys based on the requirement.

Can a foreign key be many to many?

These foreign key fields are populated with data as records in the join table are created from either table it joins. A typical example of a many-to many relationship is one between students and classes. A student can register for many classes, and a class can include many students.

Can a table have multiple primary keys can it have multiple foreign keys?

The short answer is no, a table is not allowed to contain multiple primary keys , as that goes against the fundamental principles of relational database design (see: [database normalisation](https://en.wikipedia.org/wiki/Database_normalisation) and [Third normal form](https://en.wikipedia.org/wiki/Third_normal_form) ).

Can you have multiple foreign keys from the same parent table?

In a word, yes. You can have as many foreign keys as you want referencing the same primary key.


2 Answers

You could do this:

 post:
  * post_id (PK)
  * title
  * body

 photo:
  * photo_id (PK)
  * filepath

 comment:
  * comment_id (PK)
  * body

 comment_to_post
  * comment_id (PK) -> FK to comment.comment_id
  * post_id (PK) -> FK to post.post_id

 comment_to_photo
  * comment_id (PK) -> FK to comment.comment_id
  * photo_id (PK) -> FK to photo.photo_id

There's still the possibility of having a comment that belongs to two different items. If you think that would be an issue I can try to improve the design.

like image 82
Álvaro González Avatar answered Oct 21 '22 03:10

Álvaro González


Find something common to post, profile, etc -- I have used Entity for a lack of better word, then subtype.

  • In this model one entity can have many comments, one comment belongs to one entity only.

alt text

like image 24
Damir Sudarevic Avatar answered Oct 21 '22 04:10

Damir Sudarevic