作者选择了 开放式互联网 / 自由言论基金作为 写给捐赠计划的一部分接受捐款。
介绍
Sequelize是一个基于 Node.js的对象关系地图器,可以轻松地使用 MySQL, MariaDB, SQLite, PostgreSQL)数据库,等等。一个 Object Relational Mapper通过将数据库作为对象来处理数据库记录等功能。Sequelize具有强大的迁移机制,可以将现有数据库方案转化为新版本。总体而言,Sequelize为数据库同步、热情加载、关联、交易和数据库迁移提供了很好的支持,同时缩短开发时间并防止SQL注入。
在本教程中,您将在本地开发环境中安装和配置Sequelize with MySQL。接下来,您将使用Sequelize创建数据库和模型,以及执行插入
,选择
和删除
操作。
前提条件
要完成本教程,您将需要:
- 运行 Node.js 的开发环境. 要设置此设置,请遵循操作系统的教程 如何安装 Node.js 和创建本地开发环境
- MySQL 安装在工作环境中。 遵循环境的教程 如何安装 MySQL,包括创建用户的步骤。
- 熟悉 JavaScript 和 MySQL 查询,您可以使用 How To Code in JavaScript 系列和教程 An Introduction to Queries in MySQL] 开发。
本教程已在 Node.js 版本 14.17.6 和 macOS Catalina 版本 6.14.15 上测试。
步骤 1 – 安装和配置 Sequelize
在此步骤中,您将安装Sequelize并创建连接到您的MySQL数据库。 要做到这一点,您首先将创建一个Node.js应用程序。 然后,您将安装Sequelize,配置MySQL数据库,并开发一个简单的应用程序。
安装 Sequelize
首先,创建一个项目文件夹,在这个例子中,你可以使用Hello-world
。 创建文件夹后,使用终端导航到文件夹:
1mkdir hello-world
2cd hello-world
然后,使用以下命令创建 Node.js 样本应用程序:
1npm init
接下来,您将被要求回答一些设置问题。 使用以下输出进行配置。 按ENTER
来使用显示的默认值,并确保将主要输入点设置为server.js
。
输出将看起来如下,这将填充 package.json
文件:
1[label /hello-world/package.json]
2{
3 "name": "hello-world",
4 "version": "1.0.0",
5 "description": "",
6 "main": "server.js",
7 "scripts": {
8 "test": "echo \"Error: no test specified\" && exit 1"
9 },
10 "author": "",
11 "license": "ISC"
12}
接下来,在项目文件夹中创建一个空的 server.js
文件:
1touch server.js
按照上面的步骤,您的最终文件夹结构将看起来如下:
1hello-world/
2├─ package.json
3├─ server.js
现在您可以使用以下命令安装 Sequelize:
1npm i [email protected]
<$>[注]
注: 此命令安装版本 6.11.0. 如果您需要安装最新版本,请运行 npm i sequelize
。
经过这些更新,package.json
文件现在看起来像这样:
1[label /hello-world/package.json]
2{
3 "name": "hello-world",
4 "version": "1.0.0",
5 "description": "",
6 "main": "server.js",
7 "scripts": {
8 "test": "echo \"Error: no test specified\" && exit 1",
9 "start": "node server.js"
10 },
11 "author": "",
12 "license": "ISC",
13 "dependencies": {
14 "sequelize": "^6.11.0"
15 }
16}
在依赖
部分中,您现在将看到一个 Sequelize 依赖。
您已经设置了项目并安装了 Sequelize。接下来,您将创建一个样本数据库以连接。
创建一个样本数据库
作为前提的一部分,您安装并配置了MySQL,其中包括创建用户,现在您将创建一个空的数据库。
要做到这一点,您首先需要登录到您的MySQL实例。如果您在远程运行,您可以使用您喜欢的工具。如果您正在使用本地运行的MySQL实例,您可以使用以下命令,以您的MySQL用户名替换您的_username:
1mysql -u your_username -p
-u
是用户名,如果帐户使用密码安全,则通过 -p
选项。
MySQL 服务器会询问您的数据库密码,输入您的密码,然后按ENTER
。
登录后,使用以下命令创建名为hello_world_db
的数据库:
1CREATE DATABASE hello_world_db;
要验证您是否成功创建了数据库,您可以使用以下命令:
1SHOW DATABASES;
您的输出将类似于此:
1+--------------------+
2| Database |
3+--------------------+
4| hello_world_db |
5| information_schema |
6| mysql |
7| performance_schema |
8| sys |
9+--------------------+
创建样本数据库后,从MySQL服务器中断连接:
1mysql> QUIT
现在,您需要为您选择的数据库安装手动驱动程序。由于Sequelize仅提供ORM功能,它不包括内置的数据库驱动程序。因此,您需要根据您的偏好安装驱动程序。
1npm install --save mysql2
在这种情况下,您正在使用MySQL的驱动程序。
<$>[注] 注: 由于本教程使用MySQL作为数据库,您正在使用一个驱动程序。
npm install --save pg pg-hstore # Postgres
npm install --save mysql2
npm install --save mariadb
npm install --save sqlite3
npm install --save tedious # Microsoft SQL Server
美元
现在你有一个样本数据库,你可以创建你的第一个 Sequelize 应用程序与数据库连接。
连接到MySQL数据库
在本节中,您将使用 Sequelize 将 Node.js 应用程序连接到 MySQL 数据库。
若要连接到数据库,请打开server.js
以使用nano
或您偏好的代码编辑器进行编辑:
1nano server.js
在新的Sequelize()
方法中,通过以下方式传输MySQL服务器参数和数据库凭据,以您的MySQL用户凭据取代DATABASE_USERNAME
和DATABASE_PASSWORD
:
1[label /hello-world/server.js]
2const Sequelize = require("sequelize");
3const sequelize = new Sequelize(
4 'hello_world_db',
5 'DATABASE_USERNAME',
6 'DATABASE_PASSWORD',
7 {
8 host: 'DATABASE_HOST',
9 dialect: 'mysql'
10 }
11);
如果您使用本地安装的 MySQL 服务器,您可以将DATABASE_HOST
替换为localhost
或127.0.0.1
作为值。
同样,如果您正在使用远程服务器,请确保将数据库连接值相应地替换为适当的远程服务器详细信息。
<$>[注] 注: 如果您正在使用任何其他数据库服务器软件,您可以相应地更换方言参数。 `方言:'mysql','mariadb', 'postgres','mssql'. <$>
接下来,拨打一个 promise-based authenticate()
方法来实时化数据库连接到应用程序. 要做到这一点,请将以下代码块添加到您的 server.js
文件:
1[label /hello-world/server.js]
2...
3
4sequelize.authenticate().then(() => {
5 console.log('Connection has been established successfully.');
6}).catch((error) => {
7 console.error('Unable to connect to the database: ', error);
8});
在这里,数据库连接是默认开放的,可以用于所有查询的相同连接. 每当你需要关闭连接时,请在这个authenticate()
呼叫后,拨打sequelize.close()
方法。 有关Sequelize的更多信息,请参阅他们的 开始指南。
Sequelize 提供的大多数方法都是非同步的,这意味着您可以在应用程序中运行进程,而非同步代码块在执行时。 此外,在成功执行非同步代码块后,它会返回 promise,这是进程结束时返回的值。
在此时,server.js 文件将看起来如下:
1[label /hello-world/server.js]
2
3const Sequelize = require("sequelize");
4
5const sequelize = new Sequelize(
6 'hello_world_db',
7 'DATABASE_USERNAME',
8 'DATABASE_PASSWORD',
9 {
10 host: 'DATABASE_HOST',
11 dialect: 'mysql'
12 }
13 );
14
15sequelize.authenticate().then(() => {
16 console.log('Connection has been established successfully.');
17}).catch((error) => {
18 console.error('Unable to connect to the database: ', error);
19});
保存并关闭您的文件。
在项目目录中,运行server.js
应用程序,运行以下命令:
1node server.js
你的输出将看起来像这样:
1[secondary_label Output]
2Connection has been established successfully!
您已成功创建数据库连接。
在此步骤中,您安装了 Sequelize,创建了一个样本数据库,并使用 Sequelize 连接到数据库。
步骤 2 — 使用 Sequelize 创建数据库表
现在你已经创建了一个示例的MySQL数据库,你可以使用Sequelize创建一个表,并填充数据。在Sequelize中,数据库表被称为 models。 模型是一个代表数据库的表的抽象。 模型定义了几件事来Sequelize,如表名称、列细节和数据类型。
首先,在项目目录中创建一个名为book.model.js
的新文件:
1nano book.model.js
与之前的步骤类似,添加数据库启动的序列代码,并在文件顶部添加DataTypes
的新导入:
1[label /hello-world/book.model.js]
2const { Sequelize, DataTypes } = require("sequelize");
Sequelize 包含许多内置的数据类型. 要访问这些数据类型,您可以为DataTypes
添加导入。 本教程指的是一些常用的数据类型,如STRING
,INTEGER
和DATEONLY
。
然后,包括您之前使用的行来创建与您的MySQL数据库的连接,并相应地更新您的MySQL凭证:
1[label /hello-world/book.model.js]
2...
3
4const sequelize = new Sequelize(
5 'hello_world_db',
6 'DATABASE_USERNAME',
7 'DATABASE_PASSWORD',
8 {
9 host: 'DATABASE_HOST',
10 dialect: 'mysql'
11 }
12 );
13
14sequelize.authenticate().then(() => {
15 console.log('Connection has been established successfully.');
16}).catch((error) => {
17 console.error('Unable to connect to the database: ', error);
18});
接下来,您将创建一个名为书籍
的模型,其中包括标题
,作者
,release_date
和主题
ID。
1[label /hello-world/book.model.js]
2...
3
4const Book = sequelize.define("books", {
5 title: {
6 type: DataTypes.STRING,
7 allowNull: false
8 },
9 author: {
10 type: DataTypes.STRING,
11 allowNull: false
12 },
13 release_date: {
14 type: DataTypes.DATEONLY,
15 },
16 subject: {
17 type: DataTypes.INTEGER,
18 }
19});
sequelize.define()
方法定义了一个新模型,它代表了数据库中的表格. 这个代码块创建了一个名为书籍
的表格,并根据标题
,作者
,发布日期
和主题
存储书籍记录。
在此代码中,allowNull
表示模型列值不能为null
。
接下来,您将添加书籍
模型到您的数据库,然后使用sync()
方法:
1[label /hello-world/book.model.js]
2...
3
4sequelize.sync().then(() => {
5 console.log('Book table created successfully!');
6}).catch((error) => {
7 console.error('Unable to create table : ', error);
8});
在sync()
方法中,您正在要求Sequelize对数据库做一些事情. 通过此调用,Sequelize将自动执行SQL查询到数据库并创建一个表,打印消息成功创建的图表!
。
如上所述,sync() 方法是一种基于承诺的方法,这意味着它还可以执行错误处理。 在此代码块中,您将检查表是否成功创建,否则它将通过捕获方法返回错误并在输出中打印。
<$>[注]
注: 您可以通过通过强制
参数来管理模型同步,以强制创建新的表,如果它不存在,或者使用现有的表。
model.sync()
:这将创建表,如果它已经不存在。model.sync({ force: true })
:这将创建表,如果相同的表已经存在,则将其放下。
美元
最终的代码将是这样的:
1[label /hello-world/book.model.js]
2const {Sequelize, DataTypes} = require("sequelize");
3
4const sequelize = new Sequelize(
5 'hello_world_db',
6 'DATABASE_USERNAME',
7 'DATABASE_PASSWORD',
8 {
9 host: 'DATABASE_HOST',
10 dialect: 'mysql'
11 }
12 );
13
14sequelize.authenticate().then(() => {
15 console.log('Connection has been established successfully.');
16}).catch((error) => {
17 console.error('Unable to connect to the database: ', error);
18});
19
20const Book = sequelize.define("books", {
21 title: {
22 type: DataTypes.STRING,
23 allowNull: false
24 },
25 author: {
26 type: DataTypes.STRING,
27 allowNull: false
28 },
29 release_date: {
30 type: DataTypes.DATEONLY,
31 },
32 subject: {
33 type: DataTypes.INTEGER,
34 }
35});
36
37sequelize.sync().then(() => {
38 console.log('Book table created successfully!');
39}).catch((error) => {
40 console.error('Unable to create table : ', error);
41});
保存并关闭您的文件。
运行您的应用程序,使用以下命令:
1node book.model.js
您将在您的命令行中获得以下输出:
1[secondary_label Output]
2Executing (default): SELECT 1+1 AS result
3Executing (default): CREATE TABLE IF NOT EXISTS `books` (`id` INTEGER NOT NULL auto_increment , `title` VARCHAR(255) NOT NULL, `author` VARCHAR(255) NOT NULL, `release_date` DATE, `subject` INTEGER, `createdAt` DATETIME NOT NULL, `updatedAt` DATETIME NOT NULL, PRIMARY KEY (`id`)) ENGINE=InnoDB;
4Connection has been established successfully.
5Executing (default): SHOW INDEX FROM `books`
6Book table created successfully!
在输出中,你会看到返回日志中包含的消息:成功创建图表!
你可以通过检查你的数据库来验证这个消息,以查看在hello_world_db
数据库中创建的新图书
表。
要验证新表的创建,请登录您的MySQL实例:
1mysql -u YOUR_USERNAME -p
输入密码后,更改样本数据库:
1USE hello_world_db;
然后运行命令显示表:
1SHOW TABLES;
您的输出将类似于此:
1+---------------------------+
2| Tables_in_hello_world_db |
3+---------------------------+
4| books |
5+---------------------------+
61 row in set (0.00 sec)
最后,从MySQL服务器中断连接:
1mysql> QUIT
您已验证书籍
模型创建成功,使用此过程,您可以按照相同的程序创建任何数量的模型。
在此步骤中,您在数据库中创建了一个模型,并使用内置方法开始使用该模型。
步骤 3 — 使用数据库查询的 Sequelize
在此步骤中,您将使用 Sequelize 内置查询进行插入、选择、有条件条款的选择和删除。
创下新纪录
在之前的步骤中,您在数据库中创建了一个书籍
模型,在本节中,您将将数据插入到该模型中。
要开始,请从上一步复制 book.model.js
的内容. 创建一个名为 `book.controller.js' 的新文件来处理查询逻辑。
在 book.controller.js
中,找到 sync()
方法. 在 sync()
方法中,添加以下突出的行:
1[label /hello-world/book.controller.js]
2...
3
4sequelize.sync().then(() => {
5 console.log('Book table created successfully!');
6
7 Book.create({
8 title: "Clean Code",
9 author: "Robert Cecil Martin",
10 release_date: "2021-12-14",
11 subject: 3
12 }).then(res => {
13 console.log(res)
14 }).catch((error) => {
15 console.error('Failed to create a new record : ', error);
16 });
17
18}).catch((error) => {
19 console.error('Unable to create table : ', error);
20});
在这里,您将新书籍记录插入您已经创建的书籍
模型,使用sync()
方法,该方法支持将新记录添加到以前创建的模型中。
您使用创建()
方法将您需要作为对象添加到数据库的数据传递给数据库。 突出的代码部分将向现有书籍
表插入新的条目。 在本示例中,您添加了Robert Cecil Martin
的清洁代码
,该条目已被分类为3
的主题
ID。
保存并关闭文件。
使用以下命令运行应用程序:
1node book.controller.js
您的输出将看起来如下:
1[secondary_label Output]
2books {
3 dataValues:
4 { id: 1,
5 title: 'Clean Code',
6 author: 'Robert Cecil Martin',
7 release_date: '2021-12-14',
8 subject: 3,
9 updatedAt: 2021-12-14T10:12:16.644Z,
10 ...
11}
您已将新记录插入到您在数据库中创建的模型中. 您可以使用相同的过程继续添加多个记录。
选择所有记录
在本节中,您将使用findAll()
方法选择并从数据库中获取所有书籍记录,首先打开book.controller.js
并删除之前的Book.create()
方法。
1[label /hello-world/book.controller.js]
2...
3
4sequelize.sync().then(() => {
5
6 Book.findAll().then(res => {
7 console.log(res)
8 }).catch((error) => {
9 console.error('Failed to retrieve data : ', error);
10 });
11
12}).catch((error) => {
13 console.error('Unable to create table : ', error);
14});
15
16...
保存并关闭文件。
接下来,使用以下命令再次运行应用程序:
1node book.controller.js
您的输出将看起来如下:
1[secondary_label Output]
2[
3 books {
4 dataValues: {
5 id: 1,
6 title: 'Clean Code',
7 author: 'Robert Cecil Martin',
8 release_date: '2020-01-01',
9 subject: 3,
10 createdAt: 2021-02-22T09:13:55.000Z,
11 updatedAt: 2021-02-22T09:13:55.000Z
12 },
13 _previousDataValues: {
14 id: 1,
15 title: 'Clean Code',
16 author: 'Robert Cecil Martin',
17 release_date: '2020-01-01',
18 subject: 3,
19 createdAt: 2021-02-22T09:13:55.000Z,
20 updatedAt: 2021-02-22T09:13:55.000Z
21 },
22...
23]
输出包含所有书籍数据作为一个数组对象. 您成功使用Sequelize findAll()
方法返回数据库中的所有书籍数据。
选择在哪里
条款
在本节中,您将使用 where
条款选择条件的值。 使用 where
条款在获取数据时指定条件. 对于本教程,您将使用 findOne()
方法从数据库中获取特定记录 ID 的书籍。
要做到这一点,打开book.controller.js
进行编辑,删除findAll()
方法,并添加以下行:
1[label /hello-world/book.controller.js]
2...
3
4sequelize.sync().then(() => {
5
6 Book.findOne({
7 where: {
8 id : "1"
9 }
10 }).then(res => {
11 console.log(res)
12 }).catch((error) => {
13 console.error('Failed to retrieve data : ', error);
14 });
15
16}).catch((error) => {
17 console.error('Unable to create table : ', error);
18});
在这里,您使用findOne()
方法从数据库中选择特定书籍记录,并选择在哪里
。
保存并关闭文件。
接下来,运行应用程序:
1node book.controller.js
您的输出将看起来如下:
1[secondary_label Output]
2books {
3 dataValues: {
4 id: 1,
5 title: 'Clean Code',
6 author: 'Robert Cecil Martin',
7 release_date: '2020-01-01',
8 subject: 'Science',
9 createdAt: 2021-02-22T09:13:55.000Z,
10 updatedAt: 2021-02-22T09:13:55.000Z
11 },
12 ...
13}
您已成功使用哪里
条款从序列模型中获取数据,您可以在数据库应用程序中使用哪里
条款来捕获条件数据。
删除一个记录
若要从数据库模型中删除特定记录,请使用Destroy()
方法与Where
选项。 要做到这一点,请打开book.controller.js
,删除findOne()
方法,并添加以下突出的行:
1[label /hello-world/book.controller.js]
2...
3sequelize.sync().then(() => {
4
5 Book.destroy({
6 where: {
7 id: 2
8 }
9 }).then(() => {
10 console.log("Successfully deleted record.")
11 }).catch((error) => {
12 console.error('Failed to delete record : ', error);
13 });
14
15}).catch((error) => {
16 console.error('Unable to create table : ', error);
17});
在这里,您将使用Destroy()
方法删除数据库中的书籍记录,并通过Where
选项进入删除书籍的id
。
保存并关闭文件。
接下来,运行应用程序:
1node book.controller.js
你的输出将看起来如下:
1[secondary_label Output]
2Successfully deleted record.
记录已被删除。
在此步骤中,您尝试了您的数据库模型和模型查询,您启动了数据库,创建了模型,插入了记录,检索了记录,使用在哪里
条款获取了条件的记录,并删除了选定的记录。
步骤 4 – 使用 Sequelize 创建协会
在此步骤中,您将使用 Sequelize 支持的标准关联类型: one-to-one、 one-to-many 和 many-to-many 关联。
Sequelize 使用基于以下数据库关系的关联类型:
- one-to-one relationship:一对一关系意味着一个表中的记录与另一个表中的一个记录相关联。在序列方面,你可以使用
belongsTo()
和hasOne()
关联来创建这种类型的关系。 - one-to-many relationship:一对许多关系意味着一个表中的记录与另一个表中的多个记录相关联。 在序列中,你可以使用
hasMany()
关联方法来创建这种类型的关系。 - many-to-many relationship:许多 A-to-many_关系意味着一个表中的多个记录与另一个表中的多个记录相关联。在序列中,你可以使用 `
在创建这些关联之前,您首先将创建一个名为student_db
的新数据库,并为学生,课程和分级添加新的模型和一些样本数据。
要创建数据库,请遵循 步骤 1 - 安装和配置序列中的相同过程来登录MySQL并创建名为 student_db
的数据库。
创建一个与一个的关系与 belongsTo()
在本节中,您将使用 Sequelize 模型创建一对一关系. 想象一下您想要获得一个学生的细节以及他们的分级水平. 因为一个学生只能有一个分级水平,这种类型的关联是一种一对一的关系,您可以使用 belongsTo()
方法。
<$>[注]
注: belongsTo()
和 hasOne()
之间存在差异。 belongsTo()
会在源表中添加 foreignKey
,而 hasOne()
会将其添加到目标表中。
belongsTo()
方法允许您在两个 Sequelize 模型之间创建一个对一个的关系. 在本示例中,您正在使用 Student
和 Grade
模型。
创建一个名为one_to_one.js
的新文件. 正如你在上一节中所做的, 连接到MySQL数据库,包括创建连接到数据库的行,并将您的MySQL用户身份验证到文件的顶部。
1[label /hello-world/one_to_one.js]
2const { Sequelize, DataTypes } = require("sequelize");
3
4const sequelize = new Sequelize(
5 'student_db',
6 'DATABASE_USERNAME',
7 'DATABASE_PASSWORD',
8 {
9 host: 'DATABASE_HOST',
10 dialect: 'mysql'
11 }
12 );
13
14sequelize.authenticate().then(() => {
15 console.log('Connection has been established successfully.');
16}).catch((error) => {
17 console.error('Unable to connect to the database: ', error);
18});
在本节中,您将创建新的student_db
数据库中的三个模型:Student
,Grade
和Course
。
对于学生
模型,将以下代码块添加到one_to_one.js
:
1[label /hello-world/one_to_one.js]
2...
3const Student = sequelize.define("students", {
4 student_id: {
5 type: DataTypes.UUID,
6 defaultValue: DataTypes.UUIDV4,
7 primaryKey: true,
8 },
9 name: {
10 type: DataTypes.STRING,
11 allowNull: false
12 }
13});
此学生模型包含两个列: student_id
和 name
。
接下来,为Grade
模型添加一个代码块:
1[label /hello-world/one_to_one.js]
2...
3const Grade = sequelize.define("grades", {
4 grade: {
5 type: DataTypes.INTEGER,
6 allowNull: false
7 }
8});
级别
模型包含列级别
。
要演示关联,您需要将样本数据添加到数据库中。 为此,您将使用 bulk()
方法. 而不是将数据单独插入到行中, bulkCreate()
方法允许您同时插入多个行到数据库模型中。
现在,将学位
和学生
数据导入数据库中的各自模型,如下所示:
1[label /hello-world/one_to_one.js]
2...
3const grade_data = [{grade : 9}, {grade : 10}, {grade : 11}]
4
5const student_data = [
6 {name : "John Baker", gradeId: 2},
7 {name : "Max Butler", gradeId: 1},
8 {name : "Ryan Fisher", gradeId: 3},
9 {name : "Robert Gray", gradeId: 2},
10 {name : "Sam Lewis", gradeId: 1}
11]
12
13sequelize.sync({ force: true }).then(() => {
14 Grade.bulkCreate(grade_data, { validate: true }).then(() => {
15 Student.bulkCreate(student_data, { validate: true }).then(() => {
16 …
17 }).catch((err) => { console.log(err); });
18 }).catch((err) => { console.log(err); });
19}).catch((error) => {
20 console.error('Unable to create the table : ', error);
21});
在这里,您提供样本数据,并将数据导入到学生
和学位
模型中. 有了您的数据库、模型和样本数据,您可以创建关联。
在one-to-one.js
中,在student_data
块下方添加以下行:
1[label /hello-world/one_to_one.js]
2...
3Student.belongsTo(Grade);
接下来,您需要检查该关联是否正常工作. 要做到这一点,您可以通过在findAll()
方法中通过包括
参数来获取所有与关联级别相关的学生数据。
由于您需要获得学生级别,您将通过级别
作为模型. 在sequelize.sync()
方法中,如下所示,添加突出的行:
1[label /hello-world/one_to_one.js]
2...
3sequelize.sync({ force: true }).then(() => {
4 Grade.bulkCreate(grade_data, { validate: true }).then(() => {
5 Student.bulkCreate(student_data, { validate: true }).then(() => {
6 Student.findAll({
7 include: [{
8 model: Grade
9 }]
10 }).then(result => {
11 console.log(result)
12 }).catch((error) => {
13 console.error('Failed to retrieve data : ', error);
14 });
15 }).catch((err) => { console.log(err); });
16 }).catch((err) => { console.log(err); });
17}).catch((error) => {
18 console.error('Unable to create the table : ', error);
19});
完整的代码看起来如下:
1[label /hello-world/one_to_one.js]
2
3const {Sequelize, DataTypes} = require("sequelize");
4
5const sequelize = new Sequelize(
6 'student_db',
7 'DATABASE_USERNAME',
8 'DATABASE_PASSWORD',
9 {
10 host: 'DATABASE_HOST',
11 dialect: 'mysql'
12 }
13 );
14sequelize.authenticate().then(() => {
15 console.log('Connection has been established successfully.');
16}).catch((error) => {
17 console.error('Unable to connect to the database: ', error);
18});
19
20const Student = sequelize.define("students", {
21 student_id: {
22 type: DataTypes.UUID,
23 defaultValue: DataTypes.UUIDV4,
24 primaryKey: true,
25 },
26 name: {
27 type: DataTypes.STRING,
28 allowNull: false
29 }
30});
31
32const Grade = sequelize.define("grades", {
33 grade: {
34 type: DataTypes.INTEGER,
35 allowNull: false
36 }
37});
38
39const grade_data = [{grade : 9}, {grade : 10}, {grade : 11}]
40
41const student_data = [
42 {name : "John Baker", gradeId: 2},
43 {name : "Max Butler", gradeId: 1},
44 {name : "Ryan Fisher", gradeId: 3},
45 {name : "Robert Gray", gradeId: 2},
46 {name : "Sam Lewis", gradeId: 1}
47]
48
49// One-To-One association
50Student.belongsTo(Grade);
51
52sequelize.sync({ force: true }).then(() => {
53 Grade.bulkCreate(grade_data, { validate: true }).then(() => {
54 Student.bulkCreate(student_data, { validate: true }).then(() => {
55 Student.findAll({
56 include: [{
57 model: Grade
58 }]
59 }).then(result => {
60 console.log(result)
61 }).catch((error) => {
62 console.error('Failed to retrieve data : ', error);
63 });
64 }).catch((err) => { console.log(err); });
65 }).catch((err) => { console.log(err); });
66}).catch((error) => {
67 console.error('Unable to create the table : ', error);
68});
保存并关闭您的文件。
使用以下命令运行文件:
1node one_to_one.js
输出将很长,你会看到所有学生的数据与分级水平. 以下是显示学生数据的输出片段:
1[secondary_label Output]
2students {
3 dataValues:
4 { student_id: '3e786a8f-7f27-4c59-8e9c-a8c606892288',
5 name: 'Sam Lewis',
6 createdAt: 2021-12-16T08:49:38.000Z,
7 updatedAt: 2021-12-16T08:49:38.000Z,
8 gradeId: 1,
9 grade: [grades] },
10 _previousDataValues:
11...
根据您正在使用的命令行工具,输出可能以扩展视图打印或不打印,如果是扩展视图,则将扩展的级别
对象打印为输出。
在本节中,您使用Student.belongsTo(Grade);
方法调用创建了一对一关系,并根据您创建的关联获得详细信息。
通过hasMany()
创建一对多关系
在本节中,您将使用 Sequelize 模型创建一个对多人的关系. 想象一下,您希望让所有学生都与所选级别相关联。
要開始,請將「one_to_one.js」的內容複製成名為「one_to_many.js」的新檔案。在「one_to_many.js」中,移除「student_data」塊後的行。
1[label /hello-world/one_to_many.js]
2const {Sequelize, DataTypes} = require("sequelize");
3
4const sequelize = new Sequelize(
5 'student_db',
6 'DATABASE_USERNAME',
7 'DATABASE_PASSWORD',
8 {
9 host: 'DATABASE_HOST',
10 dialect: 'mysql'
11 }
12 );
13
14sequelize.authenticate().then(() => {
15 console.log('Connection has been established successfully.');
16}).catch((error) => {
17 console.error('Unable to connect to the database: ', error);
18});
19
20const Student = sequelize.define("students", {
21 student_id: {
22 type: DataTypes.UUID,
23 defaultValue: DataTypes.UUIDV4,
24 primaryKey: true,
25 },
26 name: {
27 type: DataTypes.STRING,
28 allowNull: false
29 }
30});
31const Grade = sequelize.define("grades", {
32 grade: {
33 type: DataTypes.INTEGER,
34 allowNull: false
35 }
36});
37
38const grade_data = [ {grade : 9}, {grade : 10}, {grade : 11}]
39
40const student_data = [
41 {name : "John Baker", gradeId: 2},
42 {name : "Max Butler", gradeId: 1},
43 {name : "Ryan Fisher", gradeId: 3},
44 {name : "Robert Gray", gradeId: 2},
45 {name : "Sam Lewis", gradeId: 1}
46]
在student_data
块之后,使用hasMany()
方法创建一个新的关系:
1[label /hello-world/one_to_many.js]
2...
3Grade.hasMany(Student)
hasMany()
方法允许您在两个 Sequelize 模型之间创建一个对许多的关系,在这里,您正在使用Grade
和Student
模型。
接下来,在hasMany()
行下方添加sequelize.sync()
方法,使用findAll()
方法:
1[label /hello-world/one_to_many.js]
2...
3sequelize.sync({ force: true }).then(() => {
4 Grade.bulkCreate(grade_data, { validate: true }).then(() => {
5 Student.bulkCreate(student_data, { validate: true }).then(() => {
6 Grade.findAll({
7 where: {
8 grade: 9
9 },
10 include: [{
11 model: Student
12 }]
13 }).then(result => {
14 console.dir(result, { depth: 5 });
15 }).catch((error) => {
16 console.error('Failed to retrieve data : ', error);
17 });
18 }).catch((err) => { console.log(err); });
19 }).catch((err) => { console.log(err); });
20}).catch((error) => {
21 console.error('Unable to create table : ', error);
22});
在这里,您正在尝试访问特定级别的所有学生 - 在这种情况下,所有9级的学生。
以下是完整的代码:
1[label /hello-world/one_to_many.js]
2const {Sequelize, DataTypes} = require("sequelize");
3
4const sequelize = new Sequelize(
5 'student_db',
6 'DATABASE_USERNAME',
7 'DATABASE_PASSWORD',
8 {
9 host: 'DATABASE_HOST',
10 dialect: 'mysql'
11 }
12 );
13
14sequelize.authenticate().then(() => {
15 console.log('Connection has been established successfully.');
16}).catch((error) => {
17 console.error('Unable to connect to the database: ', error);
18});
19
20const Student = sequelize.define("students", {
21 student_id: {
22 type: DataTypes.UUID,
23 defaultValue: DataTypes.UUIDV4,
24 primaryKey: true,
25 },
26 name: {
27 type: DataTypes.STRING,
28 allowNull: false
29 }
30});
31const Grade = sequelize.define("grades", {
32 grade: {
33 type: DataTypes.INTEGER,
34 allowNull: false
35 }
36});
37
38const grade_data = [ {grade : 9}, {grade : 10}, {grade : 11}]
39
40const student_data = [
41 {name : "John Baker", gradeId: 2},
42 {name : "Max Butler", gradeId: 1},
43 {name : "Ryan Fisher", gradeId: 3},
44 {name : "Robert Gray", gradeId: 2},
45 {name : "Sam Lewis", gradeId: 1}
46]
47
48// One-To-Many relationship
49Grade.hasMany(Student);
50
51sequelize.sync({ force: true }).then(() => {
52 Grade.bulkCreate(grade_data, { validate: true }).then(() => {
53 Student.bulkCreate(student_data, { validate: true }).then(() => {
54 Grade.findAll({
55 where: {
56 grade: 9
57 },
58 include: [{
59 model: Student
60 }]
61 }).then(result => {
62 console.dir(result, { depth: 5 });
63 }).catch((error) => {
64 console.error('Failed to retrieve data : ', error);
65 });
66 }).catch((err) => { console.log(err); });
67 }).catch((err) => { console.log(err); });
68}).catch((error) => {
69 console.error('Unable to create table : ', error);
70});
保存并关闭您的文件。
使用以下命令运行文件:
1node one_to_many.js
这将是相当长的,但所有9年级的学生将被返回如下:
1[secondary_label Output]
2[ grades {
3 dataValues:
4 { id: 1,
5 grade: 9,
6 createdAt: 2021-12-20T05:12:31.000Z,
7 updatedAt: 2021-12-20T05:12:31.000Z,
8 students:
9 [ students {
10 dataValues:
11 { student_id: '8a648756-4e22-4bc0-8227-f590335f9965',
12 name: 'Sam Lewis',
13 createdAt: 2021-12-20T05:12:31.000Z,
14 updatedAt: 2021-12-20T05:12:31.000Z,
15 gradeId: 1 },
16...
17 students {
18 dataValues:
19 { student_id: 'f0304585-91e5-4efc-bdca-501b3dc77ee5',
20 name: 'Max Butler',
21 createdAt: 2021-12-20T05:12:31.000Z,
22 updatedAt: 2021-12-20T05:12:31.000Z,
23 gradeId: 1 },
24...
在本节中,您使用Grade.hasMany(学生);
方法调用创建了一个对多人的关系,在输出中,您根据创建的关联获取了详细信息。
创建多对多关系使用belongsToMany()
在本节中,您将使用 Sequelize 模型创建多对多关系。 例如,想象一个学生被录取到课程中的情况。 一个学生可以录取到许多课程,一个课程可以有许多学生。 这是一个多对多关系。 要使用 Sequelize 实现这一点,您将使用模型Student
,Course
和StudentCourse
使用belongsToMany()
方法。
要开始,请创建名为 `many_to_many.js’的文件,并按以下方式添加数据库启动和身份验证代码块。
1[label /hello-world/many_to_many.js]
2
3const {Sequelize, DataTypes} = require("sequelize");
4
5const sequelize = new Sequelize(
6 'student_db',
7 'DATABASE_USERNAME',
8 'DATABASE_PASSWORD',
9 {
10 host: 'DATABASE_HOST',
11 dialect: 'mysql'
12 }
13);
14
15sequelize.authenticate().then(() => {
16 console.log('Connection has been established successfully.');
17}).catch((error) => {
18 console.error('Unable to connect to the database: ', error);
19});
接下来,您将创建多对多关系的数据库模型:学生
和课程
,然后将一些样本数据添加到这些模型中。
1[label /hello-world/many_to_many.js]
2...
3
4const Student = sequelize.define("students", {
5 student_id: {
6 type: DataTypes.UUID,
7 defaultValue: DataTypes.UUIDV4,
8 },
9 name: {
10 type: DataTypes.STRING,
11 allowNull: false
12 }
13});
14
15const Course = sequelize.define("courses", {
16 course_name: {
17 type: DataTypes.STRING,
18 allowNull: false
19 }
20});
21
22const StudentCourse = sequelize.define('StudentCourse', {
23 id: {
24 type: DataTypes.INTEGER,
25 primaryKey: true,
26 autoIncrement: true,
27 allowNull: false
28 }
29 });
30
31const course_data = [
32 {course_name : "Science"},
33 {course_name : "Maths"},
34 {course_name : "History"}
35]
36
37const student_data = [
38 {name : "John Baker", courseId: 2},
39 {name : "Max Butler", courseId: 1},
40 {name : "Ryan Fisher", courseId: 3},
41 {name : "Robert Gray", courseId: 2},
42 {name : "Sam Lewis", courseId: 1}
43]
44
45const student_course_data = [
46 {studentId : 1, courseId: 1},
47 {studentId : 2, courseId: 1},
48 {studentId : 2, courseId: 3},
49 {studentId : 3, courseId: 2},
50 {studentId : 1, courseId: 2},
51]
在这里,您创建了学生
和课程
模型,并提供了一些样本数据,您还设置了一个课程ID
,您将根据这种关系类型来检索学生。
最后,您定义了一个名为StudentCourse
的新模型,该模型管理Student
和Course
之间的关系数据。
您已完成数据库启动并将样本数据添加到数据库中,然后使用如下所示的 belongsToMany()
方法创建多对多关系:
1[label /hello-world/many_to_many.js]
2...
3Course.belongsToMany(Student, { through: 'StudentCourse'})
4Student.belongsToMany(Course, { through: 'StudentCourse'})
在belongsToMany()
方法中,您将通过
配置以模型名称作为配置选项,在这种情况下,它是StudentCourse
。
最后,您可以通过检索与相关学生的所有课程数据来检查该关联是否正常工作,您将通过在findAll()
方法中的包括
参数来做到这一点。
1[label /hello-world/many_to_many.js]
2...
3sequelize.sync({ force: true }).then(() => {
4 Course.bulkCreate(course_data, { validate: true }).then(() => {
5 Student.bulkCreate(student_data, { validate: true }).then(() => {
6 StudentCourse.bulkCreate(student_course_data, { validate: true }).then(() => {
7 Course.findAll({
8 include: {
9 model: Student,
10 },
11 }).then(result => {
12 console.log(result);
13 }).catch((error) => {
14 console.error('Failed to retrieve data : ', error);
15 });
16 }).catch((error) => {
17 console.log(error);
18 });
19 }).catch((error) => {
20 console.log(error);
21 });
22 }).catch((error) => {
23 console.log(error);
24 });
25}).catch((error) => {
26 console.error('Unable to create table : ', error);
27});
完整的代码看起来如下:
1[label /hello-world/many_to_many.js]
2const {Sequelize, DataTypes} = require("sequelize");
3
4const sequelize = new Sequelize(
5 'student_db',
6 'DATABASE_USERNAME',
7 'DATABASE_PASSWORD',
8 {
9 host: 'DATABASE_HOST',
10 dialect: 'mysql'
11 }
12);
13
14sequelize.authenticate().then(() => {
15 console.log('Connection has been established successfully.');
16}).catch((error) => {
17 console.error('Unable to connect to the database: ', error);
18});
19
20const Student = sequelize.define("students", {
21 student_id: {
22 type: DataTypes.UUID,
23 defaultValue: DataTypes.UUIDV4,
24 },
25 name: {
26 type: DataTypes.STRING,
27 allowNull: false
28 }
29});
30
31const Course = sequelize.define("courses", {
32 course_name: {
33 type: DataTypes.STRING,
34 allowNull: false
35 }
36});
37
38const StudentCourse = sequelize.define('StudentCourse', {
39 id: {
40 type: DataTypes.INTEGER,
41 primaryKey: true,
42 autoIncrement: true,
43 allowNull: false
44 }
45 });
46
47const course_data = [
48 {course_name : "Science"},
49 {course_name : "Maths"},
50 {course_name : "History"}
51]
52
53const student_data = [
54 {name : "John Baker", courseId: 2},
55 {name : "Max Butler", courseId: 1},
56 {name : "Ryan Fisher", courseId: 3},
57 {name : "Robert Gray", courseId: 2},
58 {name : "Sam Lewis", courseId: 1}
59]
60
61const student_course_data = [
62 {studentId : 1, courseId: 1},
63 {studentId : 2, courseId: 1},
64 {studentId : 2, courseId: 3},
65 {studentId : 3, courseId: 2},
66 {studentId : 1, courseId: 2},
67]
68
69Course.belongsToMany(Student, { through: 'StudentCourse'})
70Student.belongsToMany(Course, { through: 'StudentCourse'})
71
72sequelize.sync({ force: true }).then(() => {
73 Course.bulkCreate(course_data, { validate: true }).then(() => {
74 Student.bulkCreate(student_data, { validate: true }).then(() => {
75 StudentCourse.bulkCreate(student_course_data, { validate: true }).then(() => {
76 Course.findAll({
77 include: {
78 model: Student,
79 },
80 }).then(result => {
81 console.log(result);
82 }).catch((error) => {
83 console.error('Failed to retrieve data : ', error);
84 });
85 }).catch((error) => {
86 console.log(error);
87 });
88 }).catch((error) => {
89 console.log(error);
90 });
91 }).catch((error) => {
92 console.log(error);
93 });
94}).catch((error) => {
95 console.error('Unable to create table : ', error);
96});
保存并关闭文件。
使用以下命令运行文件:
1node many_to_many.js
输出将是漫长的,但将看起来有点像以下:
1[secondary_label Output]
2[ courses {
3 dataValues:
4 { id: 1,
5 course_name: 'Science',
6 createdAt: 2022-05-11T04:27:37.000Z,
7 updatedAt: 2022-05-11T04:27:37.000Z,
8 students: [Array] },
9 _previousDataValues:
10 { id: 1,
11 course_name: 'Science',
12 createdAt: 2022-05-11T04:27:37.000Z,
13 updatedAt: 2022-05-11T04:27:37.000Z,
14 students: [Array] },
15 _changed: Set {},
16 _options:
17 { isNewRecord: false,
18 _schema: null,
19 _schemaDelimiter: '',
20 include: [Array],
21 includeNames: [Array],
22 includeMap: [Object],
23 includeValidated: true,
24 attributes: [Array],
25 raw: true },
26 isNewRecord: false,
27 students: [ [students], [students] ] },
28 courses {
29 dataValues:
30 { id: 2,
31 course_name: 'Maths',
32 createdAt: 2022-05-11T04:27:37.000Z,
33 updatedAt: 2022-05-11T04:27:37.000Z,
34 students: [Array] },
35 _previousDataValues:
36...
正如您在此输出中所看到的,与相关学生的课程已被检索。在课程
块中,您将看到指示每个课程的单独id
值。例如,id: 1
与科学类的course_name: Science
相关联,而id: 2
是数学类等等。
在数据库中,您可以看到与您插入的样本数据的三个生成的表。
在此步骤中,您使用 Sequelize 创建一个对一个、一个对许多和许多对许多关联,接下来,您将使用原始查询。
步骤 5 – 使用原始查询
在此步骤中,您将在 Sequelize 中使用 原始查询。在以前的步骤中,您使用了 Sequelize 内置方法,例如 insert()
和 findAll()
,以处理数据插入和从数据库中进行选择。您可能已经注意到这些方法遵循一个特定模式来编写查询。然而,使用原始查询,您不必担心 Sequelize 内置的方法和模式。 使用您对 SQL 查询的知识,您可以在 Sequelize 中执行一系列查询,从简单到更高级。
以下是原始查询的示例,这些查询执行从特定表中选择所有值,根据条件删除所选值,并更新该表以提供的值。
1SELECT * FROM table_name;
2DELETE FROM table_name WHERE condition;
3UPDATE table_name SET y = 42 WHERE x = 12;
在 Sequelize 中,原始查询可以使用主要有两种方法:数组替换和对象替换. 当您将值传输到 SQL 查询时,您可以使用数组或对象来进行替换。
在撰写原始查询之前,您首先需要在样本数据库中提供学生数据。 按照上一节, 创建样本数据库,登录MySQL,创建名为 `sample_student_db'的数据库,然后退出MySQL。
然后,您将添加一些原始数据以开始使用原始查询。创建一个名为add_student_records.js
的新文件,并添加以下代码块,其中包含之前讨论的验证()
、同步()
和bulkCreate()
的序列方法。
1[label /hello-world/add_student_records.js]
2
3const {Sequelize, DataTypes} = require("sequelize");
4
5const sequelize = new Sequelize(
6 'sample_student_db',
7 'DATABASE_USERNAME',
8 'DATABASE_PASSWORD',
9 {
10 host: 'DATABASE_HOST',
11 dialect: 'mysql'
12 }
13 );
14
15sequelize.authenticate().then(() => {
16 console.log('Connection has been established successfully.');
17}).catch((error) => {
18 console.error('Unable to connect to the database: ', error);
19});
20
21const Student = sequelize.define("students", {
22 student_id: {
23 type: DataTypes.UUID,
24 defaultValue: DataTypes.UUIDV4,
25 primaryKey: true,
26 },
27 name: {
28 type: DataTypes.STRING,
29 allowNull: false
30 }
31});
32
33const student_data = [
34 {name : "John Baker"},
35 {name : "Max Butler"},
36 {name : "Ryan Fisher"},
37 {name : "Robert Gray"},
38 {name : "Sam Lewis"}
39]
40
41sequelize.sync({ force: true }).then(() => {
42
43 Student.bulkCreate(student_data, { validate: true }).then((result) => {
44 console.log(result);
45 }).catch((error) => {
46 console.log(error);
47 });
48
49}).catch((error) => {
50 console.error('Unable to create table : ', error);
51});
在这里,您启动数据库连接,创建模型,并在新数据库中插入一些学生记录。
保存并关闭文件。
接下来,使用以下命令运行此脚本:
1node add_student_records.js
输出将类似于以下内容。 它将相当长,但您插入的所有学生记录将如下返回。 请注意,由于 student_id
是一个自动生成的 UUID(Universally Unique Identifiers)值,它将因用户而异。
1[secondary_label Output]
2Executing (default): SELECT 1+1 AS result
3Executing (default): DROP TABLE IF EXISTS `students`;
4Connection has been established successfully.
5Executing (default): DROP TABLE IF EXISTS `students`;
6Executing (default): CREATE TABLE IF NOT EXISTS `students` (`student_id` CHAR(36) BINARY , `name` VARCHAR(255) NOT NULL, `createdAt` DATETIME NOT NULL, `updatedAt` DATETIME NOT NULL, PRIMARY KEY (`student_id`)) ENGINE=InnoDB;
7Executing (default): SHOW INDEX FROM `students`
8Executing (default): INSERT INTO `students` (`student_id`,`name`,`createdAt`,`updatedAt`) VALUES ('45d1f26c-ba76-431f-ac5f-f41282351710','John Baker','2022-06-03 07:27:49','2022-06-03 07:27:49'),('1cb4e34d-bfcf-4a97-9624-e400b9a1a5f2','Max Butler','2022-06-03 07:27:49','2022-06-03 07:27:49'),('954c576b-ba1c-4dbc-a5c6-8eaf22bbbb04','Ryan Fisher','2022-06-03 07:27:49','2022-06-03 07:27:49'),('e0f15cd3-0025-4032-bfe8-774e38e14c5f','Robert Gray','2022-06-03 07:27:49','2022-06-03 07:27:49'),('826a0ec9-edd0-443f-bb12-068235806659','Sam Lewis','2022-06-03 07:27:49','2022-06-03 07:27:49');
9[
10 students {
11 dataValues: {
12 student_id: '45d1f26c-ba76-431f-ac5f-f41282351710'`,
13 name: 'John Baker',
14 createdAt: 2022-06-03T07:27:49.453Z,
15 updatedAt: 2022-06-03T07:27:49.453Z
16 },
17 _previousDataValues: {
18 name: 'John Baker',
19 student_id: '45d1f26c-ba76-431f-ac5f-f41282351710',
20 createdAt: 2022-06-03T07:27:49.453Z,
21 updatedAt: 2022-06-03T07:27:49.453Z
22 },
23
24…
在下一节中,您将使用上面的代码块中的student_id
输出之一应用原始查询,复制它,以便您在下一节中拥有它,在那里您将使用query()
方法来代替数组和对象。
阿拉斯代替
在本节中,您将使用 query()
方法来代替数组. 使用此方法,Sequelize 可以执行原始或已准备的 SQL 查询。
要开始,请从 步骤 1复制 server.js
文件的内容,因为其中包括启动 Sequelize()
方法和数据库启动。
1[label /hello-world/array_raw_query.js]
2
3const {Sequelize, DataTypes} = require("sequelize");
4
5const sequelize = new Sequelize(
6 'sample_student_db',
7 'DATABASE_USERNAME',
8 'DATABASE_PASSWORD',
9 {
10 host: 'DATABASE_HOST',
11 dialect: 'mysql'
12 }
13 );
14
15sequelize.authenticate().then(() => {
16 console.log('Connection has been established successfully.');
17}).catch((error) => {
18 console.error('Unable to connect to the database: ', error);
19});
在文件的末尾,添加以下代码块来替换数组,确保用您在上一节中复制的student_id
值代替REPLACE_STUDENT_ID
。
1[label /hello-world/array_raw_query.js]
2...
3sequelize.query(
4 'SELECT * FROM students WHERE student_id = ?',
5 {
6 replacements: ['REPLACE_STUDENT_ID'],
7 type: sequelize.QueryTypes.SELECT
8 }
9).then(result => {
10 console.log(result);
11}).catch((error) => {
12 console.error('Failed to insert data : ', error);
13});
对于数组更换,您通过Query()
方法与 SQL 查询和配置对象. 它包含replacements
值和类型. 对于更换,您将数据作为一个数组传输,并使用问号符号(?
)来捕捉这些值。
接下来,因为您需要获取有关特定学生的数据,因此将student_id
作为第二个参数传输,然后将type: sequelize.QueryTypes.SELECT
键值对传输,您可以使用它从数据库中选择数据。
还有一些其他类型,例如QueryTypes.UPDATE
和QueryTypes.DELETE
。
下面显示了完整的代码块,在这里您连接到数据库并使用原始查询获取所选的学生数据。
1[label /hello-world/array_raw_query.js]
2
3const {Sequelize, DataTypes} = require("sequelize");
4
5const sequelize = new Sequelize(
6 'sample_student_db',
7 'DATABASE_USERNAME',
8 'DATABASE_PASSWORD',
9 {
10 host: 'DATABASE_HOST',
11 dialect: 'mysql'
12 }
13 );
14
15sequelize.authenticate().then(() => {
16 console.log('Connection has been established successfully.');
17}).catch((error) => {
18 console.error('Unable to connect to the database: ', error);
19});
20
21sequelize.query(
22 'SELECT * FROM students WHERE student_id = ?',
23 {
24 replacements: ['REPLACE_STUDENT_ID'],
25 type: sequelize.QueryTypes.SELECT
26 }
27).then(result => {
28 console.log(result);
29}).catch((error) => {
30 console.error('Failed to insert data : ', error);
31});
保存并关闭您的文件。
接下来,您可以使用以下命令运行此脚本:
1node array_raw_query.js
您将看到类似于以下的输出:
1[secondary_label Output]
2Connection has been established successfully.
3[ { student_id: 'STUDENT_ID_YOU_RETRIEVED',
4 name: 'Robert Gray',
5 createdAt: 2022-05-06T13:14:50.000Z,
6 updatedAt: 2022-05-06T13:14:50.000Z } ]
由于选择了student_id
,您的输出值可能会有所不同。
对象替代
在表面上,对象更换类似于数组更换,但将数据传输到原始查询的模式不同。
要开始,创建一个名为object_raw_query.js
的新文件,并从server.js
文件中粘贴完整的代码块,将数据库更新为sample_student_db
。
1[label /hello-world/array_raw_query.js]
2
3const {Sequelize, DataTypes} = require("sequelize");
4
5const sequelize = new Sequelize(
6 'sample_student_db',
7 'DATABASE_USERNAME',
8 'DATABASE_PASSWORD',
9 {
10 host: 'DATABASE_HOST',
11 dialect: 'mysql'
12 }
13 );
14
15sequelize.authenticate().then(() => {
16 console.log('Connection has been established successfully.');
17}).catch((error) => {
18 console.error('Unable to connect to the database: ', error);
19});
然后,将以下代码块添加到新的 object_raw_query.js
文件的末尾:
1[label /hello-world/object_raw_query.js]
2...
3sequelize.query(
4 'SELECT * FROM students WHERE student_id = :id',
5 {
6 replacements: { id: 'REPLACE_STUDENT_ID' },
7 type: sequelize.QueryTypes.SELECT
8 }
9 ).then(result => {
10 console.log(result);
11}).catch((error) => {
12 console.error('Failed to insert data : ', error);
13});
您创建一个替换
对象,将id
设置为您想要获取的学生信息:{id:
REPLACE_STUDENT_ID }
。
在查询()
中,您表示:选择 * 从学生WHERE student_id = :id’。 使用
查询()`方法,您将替换值作为一个对象,这就是为什么这种方法被称为对象替换。
以下是完整的代码:
1[label /hello-world/object_raw_query.js]
2
3const {Sequelize, DataTypes} = require("sequelize");
4
5const sequelize = new Sequelize(
6 'sample_student_db',
7 'DATABASE_USERNAME',
8 'DATABASE_PASSWORD',
9 {
10 host: 'DATABASE_HOST',
11 dialect: 'mysql'
12 }
13 );
14
15sequelize.authenticate().then(() => {
16 console.log('Connection has been established successfully.');
17}).catch((error) => {
18 console.error('Unable to connect to the database: ', error);
19});
20
21sequelize.query(
22 'SELECT * FROM students WHERE student_id = :id',
23 {
24 replacements: { id: 'REPLACE_STUDENT_ID' },
25 type: sequelize.QueryTypes.SELECT
26 }
27 ).then(result => {
28 console.log(result);
29}).catch((error) => {
30 console.error('Failed to insert data : ', error);
31});
保存并关闭文件。
接下来,使用以下命令运行此脚本:
1node object_raw_query.js
结果将类似于以下:
1[secondary_label Output]
2Connection has been established successfully.
3[ { student_id: 'STUDENT_ID_YOU_RETRIEVED',
4 name: 'Robert Gray',
5 createdAt: 2022-05-06T13:14:50.000Z,
6 updatedAt: 2022-05-06T13:14:50.000Z } ]
由于选择了student_id
,您的输出值可能会有所不同。
在此步骤中,您使用了两个不同的方法来执行原始查询:数组更换和对象更换。
结论
在本教程中,您安装并配置了Sequelize。您还创建并与模型合作,这是Sequelize的必备组件之一。最后,您创建了不同类型的关联,并使用实用示例处理原始查询。
接下来,您可以使用不同的数据类型创建数据库模型,还可以使用内置方法和原始查询来更新和删除数据库中的记录。
有关 Sequelize 的更多信息,请参阅 产品文档。