Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to model tags in the database?

I have an existing webapp and want to add a tag feature so that users can tag existing objects. The question is should I add a tag column to each object? or should I normalize it and use a tag table where each object will have a collection of tags? I am leaning towards the latter because it feels cleaner, easier to report on and easier to create a tag cloud. But since I know this has been solved 1000 times I wanted to ask and see if I am missing something?

like image 381
Artilheiro Avatar asked Feb 03 '23 09:02

Artilheiro


1 Answers

Do you foresee users needing to associate more than one tag with an object?

If not, add the TAG_ID fk to the OBJECT table. Otherwise, you'd need three tables in total to correctly model a many-to-many relationship:

OBJECT

  • OBJECT_ID (pk)

OBJECT_TAG_XREF

  • OBJECT_ID (pk, fk to OBJECT)
  • TAG_ID (pk, fk to TAG)

TAG

  • TAG_ID (pk)
like image 198
OMG Ponies Avatar answered Feb 26 '23 17:02

OMG Ponies