首页 > 解决方案 > 有没有办法将对象存储在 mySQL 数据库中?

问题描述

我有一个使用 MySQL 的数据库,称为“用户”。里面有两张桌子。“第一”和“第二”。

我使用 JavaScript 作为对象数组从表单中获取用户信息。

例如let usersInformation = [{"name":"james", "age":"30"}]

如何轻松存储每个对象数组?

过去,我创建了列,例如“name”,然后将“name”的值存储在该列中。

有没有办法将对象存储在 MySQL 数据库中。我查找了 ORM 一词,并认为这可能会有所帮助。

标签: javascriptmysqlobjectorm

解决方案


您可以使用 MySQL 的 JSON 数据类型。

mysql> create database user; 

mysql> use user
# Create a table with a json data type
mysql> create table user (json JSON); 

# Insert an array into the field
mysql> insert into user(json) values ('["first", "second", "third", "4th"]'); 

# Insert an object
mysql> insert into user(json) values('{"name": "Levi", "last": "Jr"}');

mysql> select * from user;
+-------------------------------------+
| json                                |
+-------------------------------------+
| ["first", "second", "third", "4th"] |
| {"last": "Jr", "name": "Levi"}      |
+-------------------------------------+
2 rows in set (0.00 sec)


您可以使用JSON_EXTRACT从字段中获取一些信息并在 WHERE 子句中对其进行过滤。

以下是如何使用它:JSON_EXTRACT([field], [expression])), [表达式] 是您从字段中提取信息的方式。

前任。:

mysql> select * from user where JSON_EXTRACT(user.json, '$.name') = 'Levi';
+--------------------------------+
| json                           |
+--------------------------------+
| {"last": "Jr", "name": "Levi"} |
+--------------------------------+
1 row in set (0.00 sec)

mysql> select * from user where JSON_EXTRACT(user.json, '$[0]') = 'first';
+-------------------------------------+
| json                                |
+-------------------------------------+
| ["first", "second", "third", "4th"] |
+-------------------------------------+
1 row in set (0.00 sec)

推荐阅读