模型筛选条件
506字约2分钟
2024-07-3
模型筛选条件
在模型搜索,连表查询,排序等各种操作中会包含很多条件,我们此处将讲解大部分。
查询示例
此处对部分需求展示,具体更多的查询条件在更后面。
// Op对象用于构建查询条件的操作符
import { Op } from 'sequelize'
// 因为有些的筛选条件比较多所以特别抽出来,如果不多可以合并一起写。
// 假设这是前端传过来的参数
const body= {
title: '文章标题',
create_time: '2024-03-24 00:00:00'
}
/** 筛选条件 */
const whereOptions={
// 模糊title查询包含body.title的
title: {
[Op.like]: '%'+body.title+'%'
},
// 查询create_time大于等于body.create_time
create_time: {
[Op.gte]: body.create_time
},
}
// 查询用户的所有文章
UserArticle.findAndCountAll({
// 每页十条
limit: 10,
// 从index为0 的第一页开始查。
offset: 0,
// 查询条件
where: whereOptions,
// 连表查询
include: [{
// 别名
as: 'other',
// 具体模型
model: UserArticleOther,
// 只拿取模型中look_num、like_num、msg_num、share_num这四个字段
attributes: ['look_num', 'like_num', 'msg_num', 'share_num']
}, {
as: 'user',
model: User,
attributes: ['nickname', 'icon_url',]
}],
// 排序,多个排序规则下数组嵌套形式
// 第一个参数为排序的字段名create_time,第二个参数是降序DESC,升序ASC
order: [['create_time', 'DESC']],
// 返回数据库中原始数据
raw:true
})
基础where筛选条件
在查询过程中会有很多条件过滤,以上可能并不能满足我们需求,所以还会有其他的内置方法,如下:
// 模糊查询
[Op.like]: '%'+body.title+'%'
// 大于等于
[Op.gte]: body.create_time
// 小于等于
[Op.lte]: body.create_time
// 大于
[Op.gt]: body.create_time
// 小于
[Op.lt]: body.create_time
// 不等于
[Op.ne]: body.create_time
// 满足这些条件的数据
[Op.in]: [1,2,3]
// 不在这些条件的数据
[Op.notIn]: [1,2,3]
// 满足a=5且b=6的数据
[Op.and]: [
{a: 5},
{b: 6}
]
// 满足其中任意一个的数据
[Op.or]: [
{a: 5},
{b: 6}
]
// 在这些条件之间
[Op.between]: [body.create_time, body.create_time]
// 不在这些条件之间
[Op.notBetween]: [body.create_time, body.create_time]