sequelize多条件_Node项目使用Sequelize(二)(包括条件查询、排序、分页,批量增删改等)...

本篇包括(条件查询、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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值