Sequelize 是 Node.js 的 ORM(对象关系映射)库,它能够帮助开发者在 Node.js 中轻松地操作关系型数据库。在本篇教程中,我们将着重介绍 Sequelize 的 Model 和 Instance 操作,以及如何在项目中使用这些操作。
Model 操作
Model 是 Sequelize 中的一个核心概念,它类似于关系型数据库中的表。通过 Model,我们可以定义表的结构、字段类型、关联关系等等。下面是一个定义用户表的 Model 的示例代码:
-- -------------------- ---- ------- ----- - ---------- ---------- ----- - - --------------------- ----- --------- - --- ------------------------------------------------------------- ----- ---- ------- ----- - - ----------- --- - ----- ------------------ ----------- ----- -------------- ---- -- --------- - ----- --------------------- ---------- ----- -- --------- - ----- ---------------------- ---------- ----- -- ------ - ----- ---------------------- ---------- ----- -- -- - ---------- ---------- ------- ----------- ----- ------------ ----- --- -------------- - -----
在上面的示例代码中,我们使用 Sequelize 的 Model 类来定义 User 表的结构。在 init 方法中,我们定义了 id、username、password 和 email 四个字段,以及它们的类型和约束条件。在定义完后,我们通过 module.exports 将 User Model 导出,以便在项目中使用。
定义好 Model 后,我们就可以在项目中使用它来进行 CRUD(增删改查)操作了。下面是几个常用的 Model 操作:
查询所有记录
const users = await User.findAll(); console.log(users);
上面的代码使用 findAll 方法查询 User 表中的所有记录,并将结果打印输出。
根据条件查询记录
const users = await User.findAll({ where: { username: 'admin' } });
console.log(users);上面的代码使用 findAll 方法根据条件查询 User 表中的记录,并将结果打印输出。其中,where 参数可以指定查询条件,例如上面示例中查询的是 username 为 'admin' 的记录。
创建新记录
const user = await User.create({ username: 'admin', password: '123456', email: 'admin@example.com' });
console.log(user);上面的代码使用 create 方法创建一条新的记录,并将结果打印输出。
更新记录
const result = await User.update({ email: 'new_email@example.com' }, { where: { username: 'admin' } });
console.log(result);上面的代码使用 update 方法更新 User 表中的记录,并将结果打印输出。其中,第一个参数表示需要更新的字段及其新值,第二个参数表示更新的条件。
删除记录
const result = await User.destroy({ where: { username: 'admin' } });
console.log(result);上面的代码使用 destroy 方法删除 User 表中的记录,并将结果打印输出。其中,where 参数指定需要删除的记录的条件。
Instance 操作
Instance 是 Model 的一个实例,它类似于关系型数据库中的记录。通过 Instance,我们可以对一个具体的记录进行操作。下面是一个示例代码:
const user = await User.findOne({ where: { username: 'admin' } });
user.password = '654321';
await user.save();
console.log(user);在上面的代码中,我们首先使用 findOne 方法查询 User 表中 username 为 'admin' 的记录,并将结果赋值给 user 变量。然后,我们将 user 变量的 password 属性修改为 '654321',并使用 save 方法保存修改后的结果。最后,我们将 user 变量打印输出。
除了 save 方法,Instance 还提供了很多其他的方法,例如:
update:更新一条记录。destroy:删除一条记录。getRelatedModel:查询关联模型。
结语
本篇文章中,我们介绍了 Sequelize 的 Model 和 Instance 操作,并给出了一些示例代码。通过学习本文,你可以了解如何使用 Sequelize 来操作关系型数据库,以及如何在项目中应用相关操作。希望本文能对读者有所帮助。
Source: FunTeaLearn,Please indicate the source for reprints https://funteas.com/post/67831826935627c9002933f1