简体   繁体   English

如何设置MySQL表,该表包含引用其他表的行

[英]How to setup MySQL tables that contain rows that are references to other tables

I am working on a game where the user can register, has an inventory and has weapons in that inventory. 我正在开发一个游戏,用户可以在该游戏上注册,拥有库存并拥有该库存中的武器。 I want to store this information in my database. 我想将此信息存储在数据库中。

Here is how I have set it up so far: 到目前为止,这是我的设置方法:

  • My user table contains a UserID column (along with other information). 我的用户表包含一个UserID列(以及其他信息)。

  • My inventory table contains an InventoryID column and a UserID column (the UserID corresponds to the owner of the inventory) 我的清单表包含一个InventoryID列和一个UserID列(该UserID对应于清单的所有者)

  • My Weapons table contains an InventoryID column which references the Inventory it belongs to. 我的武器表包含一个InventoryID列,该列引用了它所属的库存。

Is this the standard way of doing things? 这是标准的做事方式吗? Can I change my layout and make it simpler? 我可以更改布局并使它更简单吗? It just seems a little tedious to work with databases like this. 使用这样的数据库似乎有点乏味。

It would be so much easier if my User table had a reference to an inventory entry and that entry had an array of weapons. 如果我的用户表中有一个清单条目的引用,而该条目中有一系列武器,那就容易得多。 I've achieved this by storing references to the ID's of each entry but I can't just create a "User" php class (which has a reference to an Inventory object, which has an array of Weapon objects) by running one query to the database. 我通过存储对每个条目ID的引用来实现这一点,但是我不能通过运行一个查询来创建一个“ User” php类(它具有对Inventory对象的引用,该对象具有一个Weapon对象数组)。数据库。

Maybe there is a framework to achieve this? 也许有一个框架可以实现这一目标?

What You described is simple one-to-many relationship. 您所描述的是简单的一对多关系。

You don't need inventory table. 您不需要库存表。

You need a user table with userID as primary key and use it as a foreign key in weapons table. 您需要一个具有userID作为主键的用户表,并将其用作武器表中的外键。

With help of joins You can use one query to get all records. 在联接的帮助下,您可以使用一个查询来获取所有记录。

Have you considered a NoSQL database? 您是否考虑过NoSQL数据库? :) :)

Relational databases often require "join" tables as you describe. 关系数据库通常需要您所描述的“联接”表。 You can probably accomplish this without a join table if user to inventory is 1:1 - and 1 weapon can only belong to 1 inventory/user - just have weapons store a user ID. 如果库存用户为1:1,并且没有1个武器只能属于1个库存/用户,则无需连接表即可完成此操作,只需让武器存储一个用户ID。

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

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