【问题标题】:Sequelize search API not working as desired expressJSSequelize 搜索 API 无法按预期工作 expressJS
【发布时间】:2021-04-12 08:26:48
【问题描述】:

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

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

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

我是如何做到这一点的?

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

【问题讨论】:

    标签: javascript node.js express sequelize.js


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2023-04-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-01
      • 1970-01-01
      • 2017-05-12
      相关资源
      最近更新 更多