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
Color
Size
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.
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 (eg 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.
You can use variations dynamically. The inventory table contains your variation_ids and product_ids. So you can easily track your inventories.
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.