Question

I am working on a social news website where user posts anything, website provides the tag option to the users, the tags can be "Politics" or "Entertainment" anything which depends on users and they can choose more than one tag ... so my question is how to store the tags of post in database that particular post has respective tags and how to fetch all the post from database when particular tag is selected ... same as this stackoverflow website

Help me out....

Was it helpful?

Solution

this is sort of a huge qustion but let's try :-)

Database: it's an N:N relation so you need 3 tables 1) Posts which have an id 2) tags which have an id 3) posts_tags with post_id and tags_id this would make it possible to have several tags for one post

how to store: create post which gives you an post_id then you add the tags by inserting this newly created post_id with the assigned post_ids into the posts_tags table

how to retrieve according to a tag: select * from posts_tags where tags_id = x;

OTHER TIPS

You already have a table for you posts, e.g.

CREATE TABLE IF NOT EXISTS post (
  post_id int(11) NOT NULL,
  -- more columns as needed
  PRIMARY KEY (post_id)
);

You should have a table for valid tags, e.g.

CREATE TABLE IF NOT EXISTS tag (
  tag_id varchar(32) NOT NULL,
  PRIMARY KEY (tag_id)
);

Add your valid tags

INSERT INTO tag (tag_id) VALUES ('Entertainment'), ('Politics');

Finally you need a many-to-many relation between your posts and the tags

CREATE TABLE IF NOT EXISTS tag_to_post (
  tag_to_post_id int(11) NOT NULL AUTO_INCREMENT,
  tag_fk varchar(32) NOT NULL,
  post_fk int(11) NOT NULL,
  PRIMARY KEY (tag_to_post_id),
  FOREIGN KEY (tag_fk) REFERENCES tag(tag_id),
  FOREIGN KEY (post_fk) REFERENCES post(post_id)
);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top