sequelize 模糊查询
时间: 2023-08-29 18:11:35 浏览: 204
模糊查询
5星 · 资源好评率100%
在使用Sequelize进行模糊查询时,需要先导入Op模块。然后,可以使用Op.like来实现模糊查询。下面是一个使用Sequelize进行模糊查询的示例方法:
```javascript
const Sequelize = require('sequelize');
const Op = Sequelize.Op;
async function 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;
}
```
这个方法会根据传入的参数进行模糊查询,其中`user_name`字段会使用`Op.like`来实现模糊匹配。同时,这个方法还会返回查询结果的列表和数量。<span class="em">1</span><span class="em">2</span><span class="em">3</span>
#### 引用[.reference_title]
- *1* [Sequelize模糊查询](https://blog.csdn.net/m0_37805167/article/details/83002728)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"]
- *2* *3* [sequelize模糊查询及分页](https://blog.csdn.net/qq_23521659/article/details/124871838)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"]
[ .reference_list ]
阅读全文