Skip to content
Advertisement

How to store tags for a blog article in SQL database?

I currently am working on developing a blogging website. For this application we’re using MySQL as the database. For this application,I created a blog table which contains the following properties:

  • id
  • blog_title
  • content
  • user_id
  • updated_at
  • upvotes

I want to add tags to this table. What is the recommended way of adding tags to this table so that in the application I can search for articles/blogs based on tags ?

Advertisement

Answer

It is common to use many-to-many relationship for tags. In your case it can be a couple of tables:

tags

  • id
  • name

tag_blog

  • tag_id (foreign key to tags)
  • article_id (foreign key to articles)

You can set combination of (tag_id, article_id) as primary key. In this case it will be guaranteed that tag can be mentioned only once for the given article.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement