Implementing Comments and Likes in database Ask Question

Implementing Comments and Likes in database Ask Question

I'm a software developer. I love to code, but I hate databases... Currently, I'm creating a website on which a user will be allowed to mark an entity as liked (like in FB), tag it and comment.

I get stuck on database tables design for handling this functionality. Solution is trivial, if we can do this only for one type of thing (eg. photos). But I need to enable this for 5 different things (for now, but I also assume that this number can grow, as the whole service grows).

I found some similar questions here, but none of them have a satisfying answer, so I'm asking this question again.

The question is, how to properly, efficiently and elastically design the database, so that it can store comments for different tables, likes for different tables and tags for them. Some design pattern as answer will be best ;)

Detailed description: I have a table User with some user data, and 3 more tables: Photo with photographs, Articles with articles, Places with places. I want to enable any logged user to:

  • comment on any of those 3 tables

  • mark any of them as liked

  • tag any of them with some tag

  • また、各要素の「いいね!」の数と、特定のタグが使用された回数をカウントしたいと思います。

1番目のアプローチ:

a) のためにタグ、私は作成しますテーブル Tag [TagId, tagName, tagCounter]、私は作成します多対多関係テーブルのために:Photo_has_tagsPlace_has_tagArticle_has_tag

b) コメントについても同様です。

c) 私は作成しますテーブル LikedPhotos [idUser, idPhoto]、、LikedArticles[idUser, idArticle]LikedPlace [idUser, idPlace]いいね計算はクエリ(これは悪いことだと思います) そして...

最後の部分のこのデザインは本当に好きではありません。私にとっては嫌な匂いがします ;)


2番目のアプローチ:

ElementType [idType, TypeName == some table name]管理者(私)が以下の名前を入力するテーブルを作成します。テーブルそれはできる気に入ったコメントしたまたはタグ付き. それから私は創造するテーブル:

a)LikedElement [idLike, idUser, idElementType, idLikedElement]コメントとタグについても、それぞれ適切な列で同様にします。次に、写真を「いいね」したいときは、次のものを挿入します。

typeId = SELECT id FROM ElementType WHERE TypeName == 'Photo'
INSERT (user id, typeId, photoId)

場所については:

typeId = SELECT id FROM ElementType WHERE TypeName == 'Place'
INSERT (user id, typeId, placeId)

などなど... 2 番目のアプローチの方が良いと思いますが、このデザインにも何かが欠けているような気がします...

最後に、要素が何回「いいね」されたかのカウンターを保存するのに最適な場所はどこなのかも疑問です。考えられる方法は 2 つだけです。

  1. 要素(Photo/Article/Place)テーブル内
  2. select count() によって。

この問題に関する私の説明がより徹底したものになったと思います。

ベストアンサー1

最も拡張可能なソリューションは、1 つの「ベース」テーブル (「いいね!」、タグ、コメントに接続) だけを用意し、そこから他のすべてのテーブルを「継承」することです。新しい種類のエンティティを追加するには、新しい「継承」テーブルを追加するだけで済みます。その後、そのテーブルは自動的に「いいね!」/タグ/コメント メカニズム全体にプラグインされます。

実体関係用語では「カテゴリ」と呼ばれます(ERwin メソッド ガイド、セクション「サブタイプの関係」を参照)。カテゴリ シンボルは次のとおりです。

カテゴリー

ユーザーが複数のエンティティに「いいね!」でき、同じタグを複数のエンティティに使用できるが、コメントはエンティティ固有であると仮定すると、モデルは次のようになります。

ER 図


ちなみに、「ER カテゴリ」を実装する方法は、おおよそ 3 つあります。

  • すべてのタイプが 1 つのテーブルに表示されます。
  • すべての具体的なタイプは個別のテーブルにあります。
  • すべての具体的なタイプと抽象的なタイプは別々のテーブルにあります。

非常に厳しいパフォーマンス要件がない限り、3 番目のアプローチがおそらく最適です (つまり、物理テーブルは上の図のエンティティと 1:1 で一致します)。

おすすめ記事