1.开始使用
Sequelize 是一个基于 promise 的 Node.js ORM,它具有强大的事务支持, 关联关系, 预读和延迟加载,读取复制等功能。
npm i sequelize
npm i mysql2
const { Sequelize } = require('sequelize');
const sequelize = new Sequelize('dormitory', 'root', '12345678', {
host: 'localhost',
dialect: "mysql",
port: '3306',
});
try {
sequelize.authenticate();
console.log('Connection has been established successfully.');
} catch (error) {
console.error('Unable to connect to the database:', error);
}
// 在上面的示例中,Sequelize 是指库本身
// 而 sequelize 是指 Sequelize 的实例,它表示与一个数据库的连接.
复制代码
2.模型基础
模型是 Sequelize 的本质. 模型是代表数据库中表的抽象. 在 Sequelize 中,它是一个 Model 的扩展类.
该模型告诉 Sequelize 有关它代表的实体(数据库中国的表)的几件事,例如数据库中表的名称
以及它具有的列(及其数据类型)
.
Sequelize 中的模型有一个名称. 此名称不必与它在数据库中表示的表的名称相同. 通常,模型具有单数名称(例如,User
),而表具有复数名称(例如, Users
),当然这是完全可配置的.
2.1 定义模型
在 Sequelize 中可以用两种等效的方式定义模型:
- 调用 sequelize.define(modelName, attributes, options)
- 扩展 Model并调用 init(attributes, options)
分别来看下这两种定义模型的方式:
- 调用 sequelize.define
sequelize.define
会返回模型
const { Sequelize,DataTypes } = require('sequelize');
const sequelize = new Sequelize('dormitory', 'root', '12345678', {
host: 'localhost',
dialect: "mysql",
port: '3306',
});
复制代码
接着我们定义一个User模型
const User = sequelize.define('User', {
// 在这里定义模型属性
firstName: {
type: DataTypes.STRING,
allowNull: false
},
lastName: {
type: DataTypes.STRING
// allowNull 默认为 true
}
}, {
// 这是其他模型参数
});
console.log(User === sequelize.models.User); // true
复制代码
- 扩展 Model并调用 init
const { Sequelize,DataTypes,Model } = require('sequelize');
const sequelize = new Sequelize('dormitory', 'root', '12345678', {
host: 'localhost',
dialect: "mysql",
port: '3306',
});
class User1 extends Model {}
User1.init({
// 在这里定义模型属性
firstName: {
type: DataTypes.STRING,
allowNull: false
},
lastName: {
type: DataTypes.STRING
// allowNull 默认为 true
}
}, {
// 这是其他模型参数
sequelize, // 我们需要传递连接实例
modelName: 'User1' // 我们需要选择模型名称
});
// 定义的模型是类本身
console.log(User1 === sequelize.models.User1); // true
复制代码
在内部,sequelize.define
调用 Model.init
,因此两种方法本质上是等效的.
调用一个异步函数(返回一个Promise)model.sync(options)
. 通过此调用,Sequelize 将自动对数据库执行 SQL 查询. 请注意,这仅更改数据库中的表,而不更改 JavaScript 端的模型.
User.sync()
- 如果表不存在,则创建该表(如果已经存在,则不执行任何操作)User.sync({ force: true })
- 将创建表,如果表已经存在,则将其首先删除User.sync({ alter: true })
- 这将检查数据库中表的当前状态(它具有哪些列,它们的数据类型等),然后在表中进行必要的更改以使其与模型匹配.
3. 模型查询(基础)
3.1 INSERT 查询 .create
const user = await User.create(
{
username: 'alice123',
isAdmin: true
},
{
fields: ['username']
}
);
// 假设 isAdmin 的默认值为 false
console.log(user.username); // 'alice123'
console.log(user.isAdmin); // false
复制代码
3.2 SELECT 查询 .findAll
// 查询所有用户
const users = await User.findAll();
console.log(users.every(user => user instanceof User)); // true
console.log("All users:", JSON.stringify(users, null, 2));
复制代码
3.3 SELECT 查询特定属性
SELECT foo, bar FROM ...
Model.findAll({
attributes: ['foo', 'bar']
});
复制代码
SELECT foo, bar AS baz, qux FROM ...
Model.findAll({
attributes: ['foo', ['bar', 'baz'], 'qux']
});
复制代码
SELECT foo, COUNT(hats) AS n_hats, bar FROM ...
Model.findAll({
attributes: [
'foo',
[sequelize.fn('COUNT', sequelize.col('hats')), 'n_hats'],
'bar'
]
});
复制代码
3.4 UPDATE 查询
// 将所有没有姓氏的人更改为 "Doe"
await User.update({ lastName: "Doe" }, {
where: {
lastName: null
}
});
复制代码
3.5 DELETE 查询
// 删除所有名为 "Jane" 的人
await User.destroy({
where: {
firstName: "Jane"
}
});
复制代码
3.6 批量创建
const captains = await Captain.bulkCreate([
{ name: 'Jack Sparrow' },
{ name: 'Davy Jones' }
]);
复制代码
3.7 排序和分组
Sequelize 提供了 order
and group
参数,来与 ORDER BY
和 GROUP BY
一起使用.
3.8 限制和分页
使用 limit
和 offset
参数可以进行 限制/分页:
// 提取10个实例/行
Project.findAll({ limit: 10 });
// 跳过8个实例/行
Project.findAll({ offset: 8 });
// 跳过5个实例,然后获取5个实例
Project.findAll({ offset: 5, limit: 5 });
复制代码
3.9 其他
Sequelize 还提供了一些实用方法.
count
count
方法仅计算数据库中元素出现的次数.
console.log(`这有 ${await Project.count()} 个项目`);
const amount = await Project.count({
where: {
id: {
[Op.gt]: 25
}
}
});
console.log(`这有 ${amount} 个项目 id 大于 25`);
复制代码
max
, min
和 sum
Sequelize 还提供了 max,min 和 sum 便捷方法.
假设我们有三个用户,分别是10、5和40岁.
await User.max('age'); // 40
await User.max('age', { where: { age: { [Op.lt]: 20 } } }); // 10
await User.min('age'); // 5
await User.min('age', { where: { age: { [Op.gt]: 5 } } }); // 10
await User.sum('age'); // 55
await User.sum('age', { where: { age: { [Op.gt]: 5 } } }); // 50
复制代码