本篇包括(条件查询、AND 、OR 、NOT 、排序和分页、批量操作等)
1. 查询
查询全部
模型.findAll(findOptions: Object)
在数据库中搜索多个记录,返回数据和总计数
findOptions.where:搜索条件
findOptions.limit:记录条数限制
findOptions.offset:记录偏移
findOptions.order:记录排序方式
Sequelize 的 where 配置项完美支持了 SQL 的 where 子句的功能
const users = await UsersModel.findAll({
attributes: ['id', 'username', 'password'],
where: {
id: [4,5],
username: 'John'
}
});
// 找到之后更改一下它的password 因为findAll 返回的是一个数组
users[0].password = '111111111111111111'
users[0].save();
// 最后得到的users只有一条符合条件
键值对被转换成了 key = value 的形式,若一个对象包含多个键值对会被转换成了 AND 条件,即:k1: v1, k2: v2 转换为 k1 = v1 AND k2 = v2
2. AND 条件
const Op = Sequelize.Op;
const users = await UsersModel.findAll({
attributes: ['id', 'username', 'password'],
where: {
[Op.and]: [
{id: [4,5]},
{username: 'John'}
]
}
});
users[0].password = '105555555'
users[0].save();
console.log(users);
3. OR 条件
const Op = Sequelize.Op;
const users = await UsersModel.findAll({
attributes: ['id', 'username', 'password'],
where: {
[Op.or]: [
{id: [4,5]},
{username: 'John'}
]
}
});
users[0].password = '105555555'
users[0].save();
console.log(users);
4. not 条件
const Op = Sequelize.Op;
const users = await UsersModel.findAll({
attributes: ['id', 'username', 'password'],
where: {
[Op.not]: [
{id: [4,5]}
]
}
});
5. 其他条件 (如果你懂数据库语言下边代码看起来不难)
const { Op } = require("sequelize");
Post.findAll({
where: {
[Op.and]: [{ a: 5 }, { b: 6 }], // (a = 5) AND (b = 6)
[Op.or]: [{ a: 5 }, { b: 6 }], // (a = 5) OR (b = 6)
someAttribute: {
// Basics