如何设计具有不同类型产品的数据库

How To Design A Database With Different Types of Products

我有一家商店,目前销售三种不同类型的商品:视频游戏、控制台和电缆。我正在尝试弄清楚如何设计一个将由这三个项目使用的 table。

我在想每种类型都会有以下属性:

Video Game
- name
- console

Console
- name

Cable
- name

我想出了这个设计:

Product
- Type
- Name
- Console

所以它会翻译成这样的东西:

id | type    | name          | console
---+---------+---------------+---------
 1 | game    | Goldeneye     | N64
 2 | console | SNES          | null
 3 | cable   | HDMI          | null
 4 | game    | Smash Bros    | Wii

但对于 consolecable 类型的产品,控制台列始终为空。此外,如果我决定销售需要另一列的另一种类型的产品(即 - 电视显示器和包括屏幕尺寸),我认为这种设计可能会受到很大限制。

有没有更好的方法来设计我的table?

我环顾四周,发现这个解决方案似乎很理想:。我将创建一个引用属性 table 的通用产品 table。在这种情况下,数据库将无法强制执行属性(即 - 所有游戏都必须具有控制台属性)。

你可以轻松拥有两张桌子

1. Product
2. Attributes

Table 结构可能是这样的

Product
id | type    | name         
---+---------+---------------
 1 | game    | Goldeneye     
 2 | console | SNES          
 3 | cable   | HDMI          
 4 | game    | Smash Bros    
 5 | TV      | LG

Attributes
id | product_id | type        | value        
---+------------+-------------+---------
 1 | 1          | console     | N64
 2 | 4          | console     | Wii   
 3 | 5          | screen size | 50"

如果这能解决您的问题,请告诉我

您需要的是与 Products table 的多态关联。

有一个通用产品 table,它将具有 item_type 和 item_id:

id | item_type      | item_id
 1 | VideoGame      | 1
 2 | Console        | 1  
 3 | Cable          | 1  
 4 | VideoGame      | 2

视频游戏 table:

id | name          | price
 1 | Goldeneye     |  59
 2 | FIFA19        |  88

游戏机 Table:

id | name          | price
 1 | SNES          |  200
 2 | WhateverName  |  300

电缆Table

id | name          | price
 1 | HDMI          |  20
 2 | CAT6          |  30

现在每个产品都在产品 table 中可用,您可以在 item_iditem_type 的帮助下获得准确的产品。

这里id=4的商品其实是FIFA19的电子游戏,它的所有相关信息都可以在Consolestable中找到,比如它的价格是88。

所以基本上,您只需根据产品的类型和 ID 查询产品 table 即可找到该记录。

希望这对您有所帮助:)