Mysql – the proper way of designing database with dynamic fields in MySQL + PHP

eavMySQLPHP

I need help on designing a proper structure for a database table with dynamic fields. I am using MySql with PHP and the system I'm currently working on (inventory system) requires a table that accepts user-generated data categories. I'm really not good with this so any help will be greatly appreciated.

This is what I have right now (I know it's in really bad design please help)

Inventories can have different types (e.g Food, Clothes, etc) and details are dynamic based on what will be supplied by user (e.g Size, Brand, etc).

I have inventories_tbl:

+-------------------+
| inventories_tbl   |
+-------------------+
| id                |
| item_name         |
| inventory_type_id |
| description       |
| cost              |
| price             |
| quantity          |
| created_at        |
| updated_at        |
+-------------------+

then I have the inventory_types_tbl:

+--------------------+
|inventory_types_tbl |
+--------------------+
| id                 |
| name               | (e.g Food, Beverages, Clothing,etc)
| display_name       |
| created_at         |
| updated_at         |
+--------------------+

here comes the problematic part, I need to store dynamic inventory details according to what type of inventory type the item is. (e.g Food = 'expiration date', etc then if in Beverages = 'net volume', 'alcohol content', etc)

So I created a inventory_attributes_tbl:

    +-------------------+
 | inventory_attributes_tbl |
    +-------------------+
    | id                |
    | name              | (e.g size, weight, model number, serial number etc)
    | inventory_type_id |
    | field_name        |
    | created_at        |
    | updated_at        |
    +-------------------+

Then I have the inventory_attributes_values_tbl where I store the value of the attributes of a given inventory:

    +-------------------------+
  inventory_attributes_values_tbl
    +-------------------------+
    | id                      |
    | inventory_attributes_id |
    | inventory_id            |
    | value                   |
    | created_at              |
    | updated_at              |
    +-------------------------+

This setup makes the item delete/update so complicated and I also need to create a reports later on about based on the dynamic details of an item like graphs and this setup makes the query so slow and actually made the server to hang on querying just 10k+ of results. Any opinions are appreciated. Thanks in advance.

Best Answer

Its possible to use type JSON

https://dev.mysql.com/doc/refman/8.0/en/json.html

this negates the need for a table of custom fields, however if you need to do join/look ups on this data, it will be difficult.