what the best way to add multiple tags to a blog post?
i really want to add multiple tags to a blog post when a user selects them from a field, but i was wondering in terms of storing the tags in mysql, shall i have field to hold all tags, or shall store one by one i.e.
tags_field = (cats ,animals, fur)
OR
id1 cats
id2 animals
id3 fur
i was thinking to use the first example and then explode the lists and sepearte them into single tags when presenti开发者_StackOverflowng them to the user!!! :)) thanks
You should use three tables :
- One table where you store the posts ; one post per row
- One table where you store the tags ; one tag per row
- And one join-able, where you store the couples
tag_id + post_id
This way, one tag can be used by several posts, and one post can have several tags -- and there is no duplication of data of any kind.
So, basically, your tables would look like this :
posts
- id ; primary key
- date
- title
- content
tags
- id ; primary key
- name
posts_tags
- tag_id ; primary key ; foreign key to tags.tag_id
- post_id ; primary key ; foreign key to posts.post_id
If you go with the first approach you will have difficulties in querying. For example you will not be able to easily find all posts that are tagged "cats". If you go with the second approach that will not be a problem.
In other words you should have postId_tag table to map the post and the tag.
精彩评论