简体   繁体   中英

SQL to implement n-n relationship for Multiple Categories in MySQL & PHP

I wish to know what SQL is needed to be passed to implement multiple categories for an article.

I have created 3 tables.

ARTICLES:
id, title, content

CATEGORIES:
id, name

RELATION:
article_id, cat_id

I am successfully able to create the first two tables, and store data in them when user submits the form. But, I have no clue how to update the RELATION table. I searched on stackoverflow, and I learned that I need to use a many to many relationship. I have idea about it. But, I do not know how to do it practically ie the SQL.

The Categories are obviously added while the post is published, So i need to update this table only after the first two tables have been updated.

If someone can guide me to a tutorial or in the right direction I shall be greatful.

This should be taken care of by your SQL DBMS. For example, if you set your relationship's foreign keys to cascade delete or update, when something changes in the parent, the children will also be deleted/updated. Can you give me an example of an update that you would expect to make to the first two tables and the resulting update to the RELATION table?

Assuming that post and article are synonyms, then each time a new post is published and its category is determined you need to 'INSERT' a record into 'RELATION' table.

When you originally create tables you will need to identify Primary and Foreign keys (CONSTRAINTS) and (if so desired) specify whether CASCADE should be enabled.

Apparently you already know how to CREATE tables and INSERT rows.

You may want to Google for PRIMARY KEY, FOREIGN KEY, CASCADE ON DELETE in conjunction with MYSQL and PHP.

Also see if the following helps any: How do I use on delete cascade in mysql? .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM