简体   繁体   English

数据库设计建议

[英]Database Design Suggestion

I am building a shopping cart system on my localserver for practice.我正在我的本地服务器上构建一个购物车系统进行练习。

Now, I am using sessions to insert the product to the MySQL database, but I am creating a table for each of the sessions.现在,我正在使用会话将产品插入 MySQL 数据库,但我正在为每个会话创建一个表。 I know this is not an ideal way to do things.我知道这不是做事的理想方式。

My question:我的问题:

Should I define a number of rows in the sessions table, so that there will be a maximum number of items added to the cart?我是否应该在会话表中定义一些行,以便将最大数量的项目添加到购物车中?

So if I re design the table it would be因此,如果我重新设计桌子,那将是

User INT NULL,
product_1 INT NULL,
product_2 INT NULL,
...
....

I know that creating a table for each of the orders will only cause problems in the future我知道为每个订单创建一个表只会在将来引起问题

No, this design will be incredibly difficult to maintain.不,这种设计将难以维护。 Instead, have one table that will hold all cart data;取而代之的是,有一张表来保存所有购物车数据; something like:就像是:

User    Product    Quantity
2       5          1
2       3          3
2       7          1
3       5          2
3       6          2

where the "user" column is a foreign key on the user table (or cart table, whichever), and the "product" column is a foreign key on the product table.其中“用户”列是用户表(或购物车表,以任何一个为准)上的外键,“产品”列是产品表上的外键。 That way there is no restriction on the number of unique products in the cart at one time.这样,一次购物车中唯一产品的数量就没有限制。

It would probably be better to check number of items in cart before adding a new item to the database.在将新商品添加到数据库之前检查购物车中的商品数量可能会更好。 If number of cart items is equal to the maximum, then don't allow another item to be added or row to be added to database.如果购物车商品的数量等于最大值,则不允许添加其他商品或将行添加到数据库中。 I don't think it is possible to set a maximum number of rows in an SQL table and if it is possible, it probably isn't good practice.我认为不可能在 SQL 表中设置最大行数,如果可能的话,这可能不是一个好习惯。

Why not have a single table which holds all cart items (for all users) and store a unique customer ID in the Session variable which references to a row in the SQL cart table.为什么不使用一个表来保存所有购物车项目(针对所有用户)并在 Session 变量中存储唯一的客户 ID,该变量引用 SQL 购物车表中的一行。

Something like this...像这样的东西...

Columns: CustomerID |列:客户 ID | ProductID |产品编号 | QTY数量

Row 1: 1293993933 |第 1 行:1293993933 | 393939399 | 393939399 | 3 3
Row 2: 1293993933 |第 2 行:1293993933 | 339933992 | 339933992 | 4 4

Store the customer ID in a session variable ($_SESSION['CustomerID'] if you're using PHP)将客户 ID 存储在 session 变量中(如果您使用的是 PHP,则为 $_SESSION['CustomerID'])

Do a select count SQL query each time a product is added to cart.每次将产品添加到购物车时,执行 select 计数 SQL 查询。 If it equals maximum allowed cart items, don't allow user to run the insert into SQL command.如果它等于最大允许购物车项目,则不允许用户运行插入 SQL 命令。

Hope this helps希望这可以帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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