首先模糊查询要用到Op,一定要导入,否则会报错
// 使用模糊查询需要先引入Op
const seq = require('sequelize');
const Op = seq.Op;
然后是查数量,本人习惯是先查数量,不为0再去查详细数据:
这里的 user_name就是本人要检索的字段, ${user_name} 中的user_name是前端传的:
let count = await User.count({
where: {
user_name: {
[Op.like]: `%${user_name}%`
},
}
});
查详细列表同理,使用 attributes 过滤掉密码字段,使用 limit和offset来分页,pageSize和pageIndex是前端传的分页数据;
let res = await User.findAll({
attributes: {exclude: ['password']},
where: {
user_name: {
[Op.like]: `%${user_name}%`
},
},
limit: pageSize,
offset: (pageIndex - 1) * pageSize
});
最后贴上完整的方法,可供大家参考:
// 使用模糊查询需要先引入Op
const seq = require('sequelize');
const Op = seq.Op;
async getUserList({id, user_name, is_admin, pageInfo}) {
let whereObj = {};
id && Object.assign(whereObj, {id});
is_admin && Object.assign(whereObj, {is_admin});
// 加入模糊查询
user_name && Object.assign(whereObj, {
user_name: {
[Op.like]: `%${user_name}%`
},
});
// 查数量
let count = await User.count({where: whereObj});
let res;
if (count !== 0) {
let _pageInfo = {};
if (pageInfo) {
let {pageIndex, pageSize} = JSON.parse(pageInfo);
_pageInfo = {
limit: pageSize,
offset: (pageIndex - 1) * pageSize
}
}
res = await User.findAll({
attributes: {exclude: ['password']},
where: whereObj,
..._pageInfo
});
}
return {list: res, count: count} || null;
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)