Designing a database that handles inventory tracking with product variations

為{幸葍}努か 提交于 2020-01-14 06:19:06

问题


I am designing a database for a project that handles inventory management for shops.

Basically, each Product can have the variations Color, and Size, and obviously, the number of products (stock) of each possible variation will vary.

Example:

[
    {
        "product": "Plain T-Shirt",
        "color": "Red",
        "size": "Medium",
        "stock": 10,
    },
    {
        "product": "Plain T-Shirt",
        "color": "Red",
        "size": "Large",
        "stock": 2,
    },

]

Here, the same product (Plain T-Shirt) has different stocks for different variations. As you can probably imagine, I need to be able to update each stock independently.

So, what would be the most efficient way to design such a database? I am using PostgreSQL, so the design needs to be relational, but I also have access to JSON fields.

Right now, my current design looks sort of like this:

Product

  • Name (Character field)
  • Quantities (JSON field)

Color

  • Name (Character field)
  • Product (Foreign Key of Many-to-One Relationship)

Size

  • Name (Character field)
  • Product (Foreign Key of Many-to-One Relationship)

The colors, and sizes can be dynamically added by the user, so the system has to compensate for that.

Regarding the Quantities field, lets say a product P1 has the colors 'Red', and 'Green', and the sizes 'S', and 'M'. I am trying to make the Quantities field something like this: 4 keys of all the possible combinations: (Red, S), (Red, M), (Green, S), (Green, M) with values representing the stock those variations currently have in inventory.

So, my question is this: Am I on the right path? Is this design effective or is there a better way to do this? Thanks.


回答1:


The problem I see in your design is that for every product that is colored 'Red' you'd have a record for 'Red' in the colors table. Same with the sizes. And then using JSON to define the quantities would create a lot of opportunities for inconsistencies (e.g. if you delete a color from the colors table and then you forget to delete the quantity, it's not very 'relationy').

Here's how I would do it: Using a trenary relationship.

You tables would look something like this:

PRODUCTS(id,name,...)
COLORS(id,name,...)
SIZES(id,size_label,...)
STOCKS(id,product_id,color_id,size_id,quantity)

The STOCKS table represents the trenary relationship.

This way you can keep things separate enough and it's easier to keep track of your stock using a single query to do it.



来源:https://stackoverflow.com/questions/41911659/designing-a-database-that-handles-inventory-tracking-with-product-variations

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!