简体   繁体   中英

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).

  • My inventory table contains an InventoryID column and a UserID column (the UserID corresponds to the owner of the inventory)

  • My Weapons table contains an InventoryID column which references the Inventory it belongs to.

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.

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.

With help of joins You can use one query to get all records.

Have you considered a NoSQL database? :)

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.

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.

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