如何使用 sequelize node.js 进行正确的搜索和过滤

How to do a proper search and filter with sequelize node.js

所以我正在尝试在我的应用程序上创建搜索和过滤功能。 在前面你可以:

这是我在后端的控制器代码

static async show(req, res) {
    let { nama, type } = req.params;

    if (!nama) {
      nama = "";
    }
    if (!type) {
      type = "";
    }
    try {
      let car = await Car.findAll({
        order: [["id", "ASC"]],
        include: [
          {
            model: CarsImage,
            where: { primary: true },
          },
        ],
        where: {
          [Op.and]: [
            {
              nama: {
                [Op.iLike]: "%" + nama + "%",
              },
            },
            {
              type: {
                [Op.iLike]: "%" + type + "%",
              },
            },
          ],
        }
      });

      res.status(200).json(car);
    } catch (err) {
      res.status(500).json(err.message);
    }
  }

问题如下:

  1. 单独搜索功能

2 按类型筛选的搜索功能

  1. 单独按类型过滤

我知道我遇到问题 2 的原因是因为它仍然使用我数据库中的类型列过滤那个空字符(在清除 typeInput 状态之后),但我想不出更好的逻辑来做到这一点正确。

欢迎任何建议或全新的逻辑!如果您需要更多详细信息,也请告诉我。

以上代码[Op.and],你要实现的是全文搜索,

`name = ford, type = fcar`
example case1: when you search f ur search will return result because f is in both name and type, simplifying this true  && true  = true
example case2: when you type c it will not because character c is not present in name but present in type, simplifying this false && true  = false 

有问题的当前代码returns 数据如果名称、类型具有相同的字符

尝试使用 [Op.or],这在搜索许多值时更有意义

原来我路由设置错了。并在前端更正并添加一些调整后,一切正常

我之前的路线:

router.get("/:type?/:nama?", CarController.show);

更正的路线:

router.get("/type/:type?/nama/:nama?", CarController.show);