I am creating a social network. It has several objects, such as news, photos, which may contain comments. Since all comments have the same columns and behave the same, and the only difference is in their type - news, photos or something else that needs to be added in the future - I decided to create one table for all comments with a column named type . It worked fine until I decided to add foreign keys to my database schema.
The comment table has a parent column, which refers to the id table of the news or photo table, depending on the type column.
The problem is that I cannot add a foreign key that refers to a previously unknown table, and even more, which refers to several tables at once.
The entire database now uses foreign keys, except for this parent column in the comment table. This bothers me because this is the only place where I cannot add the foreign key.
I am sure I cannot create such a foreign key; something in my database project needs to be changed. I decided to create one table for comments in order to be ready to add new types of comments for new entities in the future - video, music, article, etc. - and not run hellish care when I want to add one new column for all comments.
If I absolutely need to create a separate table for each type of comment in order to make full use of foreign keys, I will do it. But perhaps another common solution to this problem already exists, and I just don't know about it?
Perhaps I need to create some kind of link table that links the comment table with tables of other entities? But maybe this solution is even more complicated than creating a separate table for each type of comment?
Maybe I should have several columns in the comment table, for example newsId , photoId , to which I can add a foreign key?
These solutions simply do not seem elegant to me, or I just misunderstand something. My general idea of ββthis problem may just be wrong. That is why I am here. Share your ideas.
database database-design foreign-keys
Elnur abdurrakhimov
source share