Sequelize 搜索 API 无法正常工作 expressJS
Sequelize search API not working as desired expressJS
我想搜索所有列并显示搜索结果。
我是 sequelize 的新手所以使用了这段代码,但是这里它正在检查完全匹配
我也想显示部分匹配项的详细信息
我该如何实现?
router.post("/search-employees", async (req, res) => {
const searchTerm = req.body.searchTerm;
try {
const resp = await employee.findAll({
where: {
[Op.or]: [
{ name: searchTerm },
{ age: searchTerm },
{ country: searchTerm },
{ position: searchTerm },
{ wage: searchTerm },
],
},
});
res.status(200).send(resp);
} catch (e) {
res.status(400).send(e);
}
});
您可以使用类似的操作,例如 ([OP.LIKE], [OP.ILIKE])。在下面找到更新的查询。
router.post("/search-employees", async (req, res) => {
const searchTerm = req.body.searchTerm;
try {
const resp = await employee.findAll({
where: {
[Op.or]: [
{ name: { [Op.like]: '%' + searchTerm + '%'} },
{ age: { [Op.like]: '%' + searchTerm + '%'} },
{ country: { [Op.like]: '%' + searchTerm + '%'} },
{ position: { [Op.like]: '%' + searchTerm + '%'} },
{ wage: { [Op.like]: '%' + searchTerm + '%'} }
],
},
});
res.status(200).send(resp);
} catch (e) {
res.status(400).send(e);
}
});
我想搜索所有列并显示搜索结果。
我是 sequelize 的新手所以使用了这段代码,但是这里它正在检查完全匹配
我也想显示部分匹配项的详细信息
我该如何实现?
router.post("/search-employees", async (req, res) => {
const searchTerm = req.body.searchTerm;
try {
const resp = await employee.findAll({
where: {
[Op.or]: [
{ name: searchTerm },
{ age: searchTerm },
{ country: searchTerm },
{ position: searchTerm },
{ wage: searchTerm },
],
},
});
res.status(200).send(resp);
} catch (e) {
res.status(400).send(e);
}
});
您可以使用类似的操作,例如 ([OP.LIKE], [OP.ILIKE])。在下面找到更新的查询。
router.post("/search-employees", async (req, res) => {
const searchTerm = req.body.searchTerm;
try {
const resp = await employee.findAll({
where: {
[Op.or]: [
{ name: { [Op.like]: '%' + searchTerm + '%'} },
{ age: { [Op.like]: '%' + searchTerm + '%'} },
{ country: { [Op.like]: '%' + searchTerm + '%'} },
{ position: { [Op.like]: '%' + searchTerm + '%'} },
{ wage: { [Op.like]: '%' + searchTerm + '%'} }
],
},
});
res.status(200).send(resp);
} catch (e) {
res.status(400).send(e);
}
});