首页 > 解决方案 > Sequelize 搜索 API 无法按预期工作 expressJS

问题描述

我想搜索所有列并显示搜索结果。

我是续集的新手,所以使用此代码来执行此操作,但是这里它正在检查完整匹配

我还想显示部分匹配的详细信息

我如何实现这一点?

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);
  }
});

标签: javascriptnode.jsexpresssequelize.js

解决方案


您可以使用类似操作,例如 ([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);
}
});

推荐阅读