- 新增
方式一:调用 build 方法后对象只存在于内存中,需要进一步调用 save 方法才会保存到数据库中。
let user = UserModel.build({
firstName: "John",
lastName: "Doe"
});
user = await user.save();
console.log(user.get({'plain': true}));
以上代码运行后,终端将会输出以下信息:
Executing (default): INSERT INTO `users` (`id`,`firstName`,`lastName`,`createdAt`,`updatedAt`) VALUES (DEFAULT,'John','Doe','2018-10-08 08:21:26','2018-10-08 08:21:26');
{ id: 5,
firstName: 'John',
lastName: 'Doe',
updatedAt: 2018-10-08T08:21:26.894Z,
createdAt: 2018-10-08T08:21:26.894Z
}
方式二:调用 create 方法后,会直接保存到数据库中。
const user = await UserModel.create({
firstName: "Sue",
lastName: "Smith"
});
console.log(user.get({'plain': true}));
以上代码运行后,终端将会输出以下信息:
Executing (default): INSERT INTO `users` (`id`,`firstName`,`lastName`,`createdAt`,`updatedAt`) VALUES (DEFAULT,'Sue','Smith','2018-10-08 08:26:11','2018-10-08 08:26:11');
{ id: 6,
firstName: 'Sue',
lastName: 'Smith',
updatedAt: 2018-10-08T08:26:11.384Z,
createdAt: 2018-10-08T08:26:11.384Z
}
- 修改
方式一:直接操作对象属性,但需要调用 save 方法后才会保存。
user.firstName = "John";
user.lastName = "Hancock";
const updatedUser = await user.save();
console.log(updatedUser.get({'plain': true}));
以上代码运行后,终端将会输出相应的 SQL 语句:
UPDATE `users` SET `firstName`='John',`lastName`='Hancock',`updatedAt`='2018-10-08 08:32:06' WHERE `id` = 7
执行更新操作时,Sequelize 将自动更新 updatedAt 字段,非常方便。
方式二:调用 update 方法,实现数据更新。
const updatedUser = await user.update({
firstName: "John",
lastName: "Hancock"
});
console.log(updatedUser.get({'plain': true}));
以上代码运行后,终端将会输出相应的 SQL 语句:
UPDATE `users` SET `firstName`='John',`lastName`='Hancock',`updatedAt`='2018-10-08 08:37:23' WHERE `id` = 8
如果想限制更新的字段,可以通过以下方式:
// 方式一
user.firstName = "John";
user.lastName = "Hancock";
const updatedUser = await user.save({ fields: ['firstName'] });
// 方式二
const updatedUser = await user.update({
firstName: "John",
lastName: "Hancock"
}, {
fields: ['firstName']
});
console.log(updatedUser.get({'plain': true}));
- 删除
const user = await UserModel.create({ // 创建新的用户
firstName: "Sue",
lastName: "Smith"
});
console.log(user.get({'plain': true}));
await user.destroy(); // 删除刚创建的用户
以上代码运行后,终端将会输出以下信息:
Executing (default): INSERT INTO `users` (`id`,`firstName`,`lastName`,`createdAt`,`updatedAt`) VALUES (DEFAULT,'Sue','Smith','2018-10-08 08:46:13','2018-10-08 08:46:13');
{ id: 9,
firstName: 'Sue',
lastName: 'Smith',
updatedAt: 2018-10-08T08:46:13.966Z,
createdAt: 2018-10-08T08:46:13.966Z
}
Executing (default): DELETE FROM `users` WHERE `id` = 9 LIMIT 1
其实如果我们启用了 paranoid(偏执)模式,destroy 的时候不会执行 DELETE 语句,而是执行一个 UPDATE 语句将 deletedAt 字段设置为当前时间(一开始此字段值为NULL)。不过需要注意的是,仅当 timestamps=true 为 true 时,paranoid 模式才能生效。
当然我们也可以使用 user.destroy({force: true}) 来强制删除,从而执行 DELETE 语句进行物理删除。
- 查询
查询全部
const users = yield User.findAll();
console.log(users);
以上代码运行后,终端将会输出相应的 SQL 语句:
SELECT `id`, `firstName`, `lastName`, `createdAt`, `updatedAt` FROM `users` AS `user`;
限制字段
const users = await UserModel.findAll({
attributes: ['id', 'firstName', 'lastName']
});
console.log(users);
以上代码运行后,终端将会输出相应的 SQL 语句:
SELECT `id`, `firstName`, `lastName` FROM `users` AS `user`;
字段重命名
const users = await UserModel.findAll({
attributes: ['id', 'firstName', ['lastName', 'lsName']]
});
console.log(users);
以上代码运行后,终端将会输出相应的 SQL 语句:
SELECT `id`, `firstName`, `lastName` AS `lsName` FROM `users` AS `user`;
- 条件查询
Sequelize 的 where 配置项完美支持了 SQL 的 where 子句的功能,功能非常强大。下面我们来简单介绍一下:
基本条件:
const users = await UserModel.findAll({
attributes: ['id', 'firstName'],
where: {
id: [1, 2],
firstName: 'John'
}
});
console.log(users);
以上代码运行后,终端将会输出相应的 SQL 语句:
SELECT `id`, `firstName` FROM `users` AS `user` WHERE `user`.`id` IN (1, 2) AND `user`.`firstName` = 'John';
可以看到,键值对被转换成了 key = value 的形式,若一个对象包含多个键值对会被转换成了 AND 条件,即:k1: v1, k2: v2 转换为 k1 = v1 AND k2 = v2。如果 value 的类型是数组类型,那么会转换成 IN 条件。
AND 条件:
const Op = Sequelize.Op;
const users = await UserModel.findAll({
attributes: ['id', 'firstName'],
where: {
[Op.and]: [
{ id: [1, 2] },
{ firstName: 'John' }
]
}
});
console.log(users);
以上代码运行后,终端将会输出相应的 SQL 语句:
SELECT `id`, `firstName` FROM `users` AS `user` WHERE (`user`.`id` IN (1, 2) AND `user`.`firstName` = 'John');
OR 条件:
const Op = Sequelize.Op;
const users = await UserModel.findAll({
attributes: ['id', 'firstName'],
where: {
[Op.or]: [
{ id: [1, 2] },
{ firstName: 'John' }
]
}
});
console.log(users);
以上代码运行后,终端将会输出相应的 SQL 语句:
SELECT `id`, `firstName` FROM `users` AS `user` WHERE (`user`.`id` IN (1, 2) OR `user`.`firstName` = 'John');
NOT 条件:
const Op = Sequelize.Op;
const users = await UserModel.findAll({
attributes: ['id', 'firstName'],
where: {
[Op.not]: [
{ id: [1, 2] }
]
}
});
console.log(users);
以上代码运行后,终端将会输出相应的 SQL 语句:
SELECT `id`, `firstName` FROM `users` AS `user` WHERE NOT (`user`.`id` IN (1, 2));
除了 and、or 和 not 操作符之外,Sequelize 还支持 notIn、like、notLike 和 between 等操作符.
其它查询方法:
查询单条记录:
方式一:调用 findById 方法:
const user = await UserModel.findById(1);
console.log(user.get({'plain': true}));
以上代码运行后,终端将会输出相应的 SQL 语句:
SELECT `id`, `firstName`, `lastName`, `createdAt`, `updatedAt` FROM `users` AS `user` WHERE `user`.`id` = 1;
方式二:调用 findOne 方法:
const user = await UserModel.findOne({
where: { firstName: 'Sue' }
});
console.log(user.get({'plain': true}));
以上代码运行后,终端将会输出相应的 SQL 语句:
SELECT `id`, `firstName`, `lastName`, `createdAt`, `updatedAt` FROM `users` AS `user` WHERE `user`.`firstName` = 'Sue' LIMIT 1;
查询并获取数量:
const result = await UserModel.findAndCountAll({
limit: 10,
offset: 0
});
console.log(result);
以上代码运行后,终端将会输出相应的 SQL 语句:
SELECT count(*) AS `count` FROM `users` AS `user`;
SELECT `id`, `firstName`, `lastName`, `createdAt`, `updatedAt` FROM `users` AS `user` LIMIT 0, 10;
排序与分页:
排序:
const users = await UserModel.findAll({
attributes: ['id', 'firstName'],
order: [
['id', 'DESC']
]
});
console.log(users);
以上代码运行后,终端将会输出相应的 SQL 语句:
SELECT `id`, `firstName` FROM `users` AS `user` ORDER BY `user`.`id` DESC;
分页:
let countPerPage = 2, currentPage = 1;
const users = await UserModel.findAll({
attributes: ['id', 'firstName'],
limit: countPerPage, // 每页多少条
offset: countPerPage * (currentPage - 1) // 跳过多少条
});
console.log(users);
以上代码运行后,终端将会输出相应的 SQL 语句:
SELECT `id`, `firstName` FROM `users` AS `user` LIMIT 0, 2;
批量操作:
插入:
const users = await UserModel.bulkCreate([
{ firstName: "John", lastName: "Doe"},
{ firstName: "Sue", lastName: "Smith"},
{ firstName: "John", lastName: "Hancock"}
]);
console.log(users);
以上代码运行后,终端将会输出相应的 SQL 语句:
INSERT INTO `users` (`id`,`firstName`,`lastName`,`createdAt`,`updatedAt`) VALUES (NULL,'John','Doe','2018-10-08 10:06:23','2018-10-08 10:06:23'),(NULL,'Sue','Smith','2018-10-08 10:06:23','2018-10-08 10
:06:23'),(NULL,'John','Hancock','2018-10-08 10:06:23','2018-10-08 10:06:23');
更新:
const Op = Sequelize.Op;
const affectedRows = await UserModel.update(
{ firstName: "King" },
{
where: {
[Op.not]: { firstName: null }
}
}
);
console.log(affectedRows);
以上代码运行后,终端将会输出相应的 SQL 语句:
UPDATE `users` SET `firstName`='King',`updatedAt`='2018-10-08 10:11:15' WHERE NOT (`firstName` IS NULL)
上面返回的 affectedRows 其实是一个数组,里面只有一个元素,表示更新的数据条数。
删除:
const affectedRows = await UserModel.destroy({
where: { firstName: 'King' }
});
console.log(affectedRows);
以上代码运行后,终端将会输出相应的 SQL 语句:
DELETE FROM `users` WHERE `firstName` = 'King'