mysqldatabase-designadjacency-list-model

Insert products into table in hierarchical relationship of category and parent in adjacent list model


i have a table category made up of adjacency list model:

id  name             parent_id
------------------------------
1   Clothing         0
2   Books            0
3   Computers        0
4   Mobiles          0
5   Movies           0
6   Music            0
7   Mens             1
8   Shirts           7
9   Formal Trousers  7
10  Jeans            7

and product_category table:

product_id fk
category_id fk
parent_id

and have a product table:

product_id
category_id
parent_id
prod_name
genre
unit price
image

how can i insert the products in table that has link to the parent-id and in-turn it has link to category. so that i can retrieve the products from parent_id and categories. and should i define parent_id as a primary key.. help appreciated..thanks in advance..


Solution

  • Assuming the relationship between products and categories is M:N, and both categories and products form a hierarchy (independent from one another), your model should look like:

    category:

    category_id PK
    parent_id FK -> category.category_id
    (other fields...)
    

    product:

    product_id PK
    parent_id FK -> product.product_id
    (other fields...)
    

    product_category:

    product_id FK -> product.product_id
    category_id FK -> category.category_id
    PK (product_id, category_id)
    

    I'm not quite sure what you mean by: "how can i insert the products in table that has link to the parent-id and in-turn it has link to category"? Assuming you know the id of the parent product and the id of the category, you can just:

    INSERT INTO product (product_id, parent_id, other fields...)
    VALUES (whatever, known parent id, other values...)
    

    And then connect it to the category:

    INSERT INTO product_category (product_id, category_id)
    VALUES (what you inserted above, known category id)